在列表中输入是不是收集复选框值?

时间:2017-11-07 06:09:51

标签: javascript jquery json

所以我的网站上有一个div,会有不同数量的问题,每个问题有两个输入。我有一个按钮,在被点击时,它调用一个JavaScript函数,将其放入一个列表中。我希望它在列表中,以便我可以将它传递给django视图并处理其中的信息。

以下代码如下:

var button = $("#serialise");

$(button).click(function() {
  var vals = [];
  $("#questions :input").each(function(index) {
    vals.push($(this).val());
  });
  console.log(vals)


});
<div id='questions'>
  <div id='q'>
    <label>Question: </label><input type="text" id="text" />
    <br>
    <label>Numeric: </label><input type="checkbox" id="checkbox" />
  </div>

  <div id='q'>
    <label>Question: </label><input type="text" id="text" />
    <br>
    <label>Numeric: </label><input type="checkbox" id="checkbox" />
  </div>
</div>

<button id="serialise">Serialise</button>

我面临的问题是,当我获得所有值时,无论是否检查复选框,我得到的列表中的值都是“打开”。

以下是一个例子:

The inputs

这就是函数产生的结果:

["Hey there", "on", "Stack Overflow", "on", "Please help <3", "on"]

2 个答案:

答案 0 :(得分:1)

用这段代码替换你的javascript,这应该可行

var button = $("#serialise");

$(button).click(function() {
    var vals = [];
    $("#questions :input").each(function(index) {

    if($(this).attr('type') == 'checkbox') {
        if($(this).prop("checked")) {
            vals.push('on');
        }
        else {
            vals.push('off');
        }
    }else {
        vals.push($(this).val());
    } 
  });
  console.log(vals)

});

答案 1 :(得分:0)

:checked选择器会有所帮助。具体如下:

$("#questions :input :checked").each(function(index){
  vals.push($(this).val());
});