开发者

Processing Checkbox Group into String

I have a form which contains a series of checkboxes, in a group. Here is the HTML -

<input type="checkbox" name="p_contents[]" value="Value 1" />
<input type="checkbox" name="p_contents[]" value="Value 2" />
<input type="checkbox" name="p_contents[]" value="Value 3" />
<input 开发者_如何学编程type="checkbox" name="p_contents[]" value="Value 4" />
<input type="checkbox" name="p_contents[]" value="Value 5" />

And I wish to process this with javascript -

var contents;
for(var i=0; i < document.forms['addForm'].elements['p_contents[]'].length; i++){   
    if(i != (document.forms['addForm'].elements['p_contents[]'].length - 1)){
        if(document.forms['addForm'].elements['p_contents[]'].checked){
            contents += encodeURIComponent(document.forms['addForm'].elements['p_contents[]'][i].value) + ",";
        }
    }else{
        if(document.forms['addForm'].elements['p_contents[]'][i].checked){
            contents += encodeURIComponent(document.forms['addForm'].elements['p_contents[]'][i].value);
        }
    }
}

I'm sure the problem is with the enumeration:

document.forms['addForm'].elements['p_contents[]'][i].checked

Is this the correct way to process a grouped checkbox form?


I'd do it this way:

var vals = [], p_contents =  document.forms['addForm']['p_contents[]'];
for(var i=0,elm;elm = p_contents[i];i++) {
    if(elm.checked) {
        vals.push(elm.value);
    }
}

and if you need the result to be a string just do

vals.join(',');

If the encodeURIComponent is needed, do that before pushing the value into the vals array like this:

vals.push(encodeURIComponent(elm.value));

So to recap - if you are looking for the exact same result your own code is giving, do this:

var contents, vals = [], p_contents =  document.forms['addForm']['p_contents[]'];
for(var i=0,elm;elm = p_contents[i];i++) {
    if(elm.checked) {
        vals.push(encodeURIComponent(elm.value));
    }
}
contents = vals.join(',');

You can see it in effect here: http://jsfiddle.net/3MRc7/


You have several checkboxes with the same name. You can't easily access them by name. Add a unique id to each and use document.getElementById(). Note that form.elements[] is indexed by integer, not name, and scans through every element on a form.

Also, if you assign a long repeating expression to a short-named var and then use that short name, it significantly improves readability of your code.


As specified by @9000 you can do the same by adding elements id and iterating it following way

for (i = 0; i < length; i++) { //you can calculate length as you did before or any alternate way
    var prefix = 'yourPrefixToId';
    if (document.getElementById(prefix + i).checked) {
    // do stuff
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜