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

时间:2013-08-12 08:10:41

标签: javascript html arrays json forms

我是.js的新手,我将从.js复选框形式的答案导出到JSON数组时出现问题。

我的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>

我的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');
                }
            });
        });

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

3 个答案:

答案 0 :(得分:9)

获取数组的值

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

获取数组的ID

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

答案 1 :(得分:5)

看看这段代码是否有帮助

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

答案 2 :(得分:1)

彗星的答案对我不起作用。这样做了:

var arrCB = {};

$("input[name='Question1']:checked").each(
    function(){
        var id = this.id;
        arrCB[id] = (this.checked ? 1 : 0)
    }
);

var text = JSON.stringify(arrCB);
alert(text);

资源:

http://blog.kevinchisholm.com/javascript/associative-arrays-in-javascript/

best practice for updating a list in database associated with checkboxes in a html form

How can I send checkboxes data into JSON array?

JQuery: Turn array input values into a string optimization