我有这些复选框:

<input type="checkbox" name="type" value="4" />
<input type="checkbox" name="type" value="3" />
<input type="checkbox" name="type" value="1" />
<input type="checkbox" name="type" value="5" />

等等。它们中大约有6个是手工编码的(即不是从db中获取的),所以它们可能会在一段时间内保持相同。

我的问题是我如何能得到他们都在一个数组(javascript),所以我可以使用他们,而使AJAX $。使用Jquery发布请求。

任何想法吗?

编辑:我只希望将选定的复选框添加到数组中


当前回答

在Javascript中,它是这样的(演示链接):

// get selected checkboxes
function getSelectedChbox(frm) {
  var selchbox = [];// array that will store the value of selected checkboxes
  // gets all the input tags in frm, and their number
  var inpfields = frm.getElementsByTagName('input');
  var nr_inpfields = inpfields.length;
  // traverse the inpfields elements, and adds the value of selected (checked) checkbox in selchbox
  for(var i=0; i<nr_inpfields; i++) {
    if(inpfields[i].type == 'checkbox' && inpfields[i].checked == true) selchbox.push(inpfields[i].value);
  }
  return selchbox;
}   

其他回答

纯JavaScript,不需要临时变量:

Array.from(document.querySelectorAll("input[type=checkbox][name=type]:checked"), e => e.value);

函数selectedValues(避署){ Var arr = []; For (var I = 0;I < ele.length;我+ +){ 如果(避署[我]。Type == 'checkbox' && ele[i].checked){ arr.push(避署[我]。value); } } 返回arr; }

格式:

$("input:checkbox[name=type]:checked").each(function(){
    yourArray.push($(this).val());
});

希望它能起作用。

var array = []
    $("input:checkbox[name=type]:checked").each(function(){
        array.push($(this).val());
    });

在勾选时添加复选框的值,在勾选时减去该值

$('#myDiv').change(function() { var values = 0.00; { $('#myDiv :checked').each(function() { //if(values.indexOf($(this).val()) === -1){ values=values+parseFloat(($(this).val())); // } }); console.log( parseFloat(values)); } }); <div id="myDiv"> <input type="checkbox" name="type" value="4.00" /> <input type="checkbox" name="type" value="3.75" /> <input type="checkbox" name="type" value="1.25" /> <input type="checkbox" name="type" value="5.50" /> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>