开发者

Help with JavaScript reading checkbox with []

i have written/modified a script to count checkboxes checked it works fine but i know need the checkbox name to read r1[] for my php scripts and now it doesn't work please help with java script...

THIS WORKS

<input name='r1' type='checkb开发者_C百科ox' value='' onClick='return GetSelectedItem2()' />

THIS DOES NOT WORK

<input name='r1[]' type='checkbox' value='' onClick='return GetSelectedItem2()' />

JAVASCRIPT

function GetSelectedItem2() {
    chosen = ""
    numCheck = 0
    len = document.f1.r1.length

    for (i = 0; i < len; i++) {


        if (document.f1.r1[i].checked) {
            numCheck++
            if (numCheck == 3) {
                alert("Only pick two date")
                document.f1;
                return false;
            }
        }
    }
}


Javascript does not enumerate the form elements like PHP does. It keeps the name as is. You have to manually iterate of the elements, check for the name "r1[]":

// pseudo code
for (var e in document.f1.elements) {   // might need for each etc.
     if (e.name == "r1[]") {
         if (e.checked) {
             numCheck++;

The array syntax access won't work, because all elements have the same name. I'm not even certain all Javascript implementations make them accessible this way (might be internally stored as dict anyway).


javascript:

function anyCheck(f){
var t=0;
var c=f['r1[]'];
for(var i=0;i<c.length;i++){
c[i].checked?t++:null;
}

if(t == 3) {
alert('You selected ' + t + ' boxes.');
document.playlist; return false;
}


}

checkbox

<input type="checkbox" name="r1[]" onclick="return anyCheck(this.form)">
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜