开发者

Using a javascript function with a checkbox array

so i have a checkbox array name "vote[]" and i want to call a function to tick all of them, atm my function is like this

function checkAll(field)  
{开发者_JS百科  
    for (i = 0; i < field.length; i++)  
        field[i].checked = true ;  
}

and i call it like this

checkAll(document.form.vote)

but it doesnt work... wutdo?

Thanks, Ben

p.s i have tried to doing

checkAll(document.form.vote[]) 

and it doesnt work.


Try:

checkAll(document.form['vote[]'])

Explanation: [] is part of the name but if you write it like form.vote[], it would be interpreted as JavaScript (probably invalid). Luckily, in JavaScript there are two ways to access object properties: Dot notation, foo.bar, and array notation, foo['bar']. The latter one comes in handy if the property is not a valid JavaScript identifier.

Further suggestion: As we don't know how your HTML look like document.form might also not work. I suggest to give the form an ID and call:

checkAll(document.getElementById('yourFormID')['vote[]'])

Update:

Works for me: DEMO


Although the original poster was able to get this working, another way (avoiding the getElementsByTagName call) would be:

checkAll(document.formname.elements['vote[]'])

Hope that helps someone in the future. :)


Try doing this with by filtering with checkbox only i.e type='checkbox'

var boxes = document.getElementsByTagName('input');
    if(boxes.type='Checkbox'){
        for (var i = 0; i < boxes.length; i++) {
            if (boxes[i].name == 'vote[]' ) {
                boxes[i].checked = true;
            }
        }
    }


Try doing this with document.getElementsByName instead:

checkAll(document.getElementsByName('vote[]'));

If that doesn't work, have a go with this, looping through all input elements.

var boxes = document.getElementsByTagName('input');
for (var i = 0; i < boxes.length; i++) {
    if (boxes[i].name == 'vote[]') {
        boxes[i].checked = true;
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜