开发者

Altering javascript, select check boxes

开发者 https://www.devze.com 2023-02-13 16:40 出处:网络
i Have this code that select all checkboxes: <html> <head> <script language=\"javascript\">

i Have this code that select all checkboxes:

<html>
<head>
<script language="javascript">
function checkAll(){
    for (var i=0;i<document.forms[0].elements.length;i++)
    {
        var e=document.forms[0].elements[i];
        if ((e.name != 'allbox') && (e.type=='checkbox'))
        {
            e.checked=document.forms[0].allbox.checked;
        }
    }
}
</script>
</head>

<body>
  <form>
    <input type="checkbox" value="on" name="allbox" onclick="checkAll();"/> Check all<br />
    <h3>Fruit</h3>
    <input type="checkbox" value="on" name="oranges" /> Oranges<br/>
    <input type="checkbox" value="on" name="bananas" /> Bananas<br/>
  </form>
</body>
</html>

How should i alter (and how it changes the logic) JavaScript that it would work in such case:

<body>
    <form id="menu">
       <input type="checkbox" value="on开发者_StackOverflow中文版" name="allbox" onclick="checkAll();"/> Check all<br />
    </form>
    <h3>Fruit</h3>
    <form id="select">
       <input type="checkbox" value="on" name="oranges" /> Oranges<br/>
       <input type="checkbox" value="on" name="bananas" /> Bananas<br/>
    </form>
</body>


There are two forms in your second example.

In your JavaScript, you have an array of all forms in the document: document.forms

Arrays in JavaScript are zero-based, so the first form is accessed with forms[0], the second with forms[1] and so on.

As the checkboxes in your example are on the second form, simply change your JavaScript to access the elements in the second form.

...
    for (var i=0;i<document.forms[1].elements.length;i++)
    {
        var e=document.forms[1].elements[i];
...

Or because your second form has an ID, you can access it via the ID like this:

...
for(var i=0;i<document.getElementById("select").elements.length;i++)
{
    var e=document.getElementById("select").elements[i];
...


You have two forms on the second page, but your script refers only to one form. You don't need to break your form into two parts (judging from your present code).

But it is possible, if you want to keep two forms. Replace document.forms[0] with document.forms[1] everywhere in your script.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号