javascript 如何将复选框数据发送到 JSON 数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18182189/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 10:59:49  来源:igfitidea点击:

How can I send checkboxes data into JSON array?

javascripthtmlarraysjsonforms

提问by fragon

I'm new to .js and I have a problem with exporting answers from .js checkboxes form into JSON array.

我是 .js 的新手,我在将 .js 复选框表单中的答案导出到 JSON 数组时遇到了问题。

My HTML:

我的 HTML:

<form>
<input type="checkbox" name="Question1" id="Answer1" value="Answer1" onclick="show_checked()"/><label for="Answer1">Answer 1</label><br/>
<input type="checkbox" name="Question1" id="Answer2" value="Answer2" onclick="show_checked()"/><label for="Answer2">Answer 2</label><br/>
<input type="checkbox" name="Question1" id="Answer3" value="Answer3" onclick="show_checked()"/><label for="Answer3">Answer 3</label><br/>
</form>

my Javascript:

我的Javascript:

function set_checked(checked) 
    $('input[name=foo]').attr('checked', checked);
}
$(document).ready(function () {
            $("input[name='Question1']").change(function () {
                var maxAllowed = 2; 
                var cnt = $("input[name='Question1']:checked").length;
                if (cnt > maxAllowed) {
                    $(this).prop("checked", "");
                    alert('Choose max. ' + maxAllowed + ' answers');
                }
            });
        });

The question is, how can I send IDs or values of the checked checkboxes into JSON array?

问题是,如何将选中复选框的 ID 或值发送到 JSON 数组中?

回答by Arun P Johny

to get values to an array

获取数组的值

var array =  $("input[name='Question1']:checked").map(function(){
    return this.value;
}).get()

to get ids to an array

获取数组的 id

var array =  $("input[name='Question1']:checked").map(function(){
    return this.id;
}).get()

回答by U.P

See if this piece of code helps

看看这段代码是否有帮助

var objArray = [];
$("input[name='Question1']:checked").each(function (index, elem) {
    var id = $(this).attr('id');
    var val = $(this).val();
    var obj = {
        Id = id,
        Value = val
    };
    objArray.push(obj);
});