处理复选框分组为字符串 [英] Processing Checkbox Group into String

查看:126
本文介绍了处理复选框分组为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含一系列复选框的表单,在一个组中。这是HTML -

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" />

我想使用javascript -

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);
        }
    }
}

是与枚举:

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

这是处理分组复选框表单的正确方法吗?

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

推荐答案

我会这样做:

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);
    }
}

如果你需要的结果是一个字符串do

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

vals.join(',');

如果需要 encodeURIComponent 然后将值推入vals数组,如下所示:

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(',');

你可以看到它在这里有效: http://jsfiddle.net/3MRc7/

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

这篇关于处理复选框分组为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆