简体   繁体   English

Javascript:如果已选中则将复选框的值与未选中的值一起推送

[英]Javascript : Pushing a value of checkbox if checked and the value of not checked together

So I have multiple checkboxes. 所以我有多个复选框。

<input type="checkbox" value="special" name="special_round[]">special1
<input type="checkbox" value="special" name="special_round[]">special2
<input type="checkbox" value="special" name="special_round[]">special3
<input type="checkbox" value="special" name="special_round[]">special4

I can only do is to push value that has checked the input 我只能做的是推送检查了输入的值

$('#click').on('click', function(e){
    e.preventDefault();
    e.stopPropagation();
var specialSequences = [];
   $('input[name="special_round[]"]:checked').each(function(i, v) {
   specialSequences.push($(v).val());
});
   alert(specialSequences);

});

The output if i check the special1 and special4 is 如果我检查special1和special4的输出是

special,special

How do i make it like this, 我该怎么做

special, 0 , 0, special //or
special, " ", " ", special

//or if i checked the special2 and speial4 the output should 
" ", special , " " , special

https://jsfiddle.net/t6fL04cm/ https://jsfiddle.net/t6fL04cm/

You need to iterate through all checkboxes and check which one is "checked" and which - is not. 您需要遍历所有复选框,并检查“已选中”和“未选中”。
Use the following approach: 使用以下方法:

...
  var specialSequences = [];
  $('input[name="special_round[]"]').each(function(i, v) {
    var current = ($(v).is(":checked"))? $(v).val() : "";
    specialSequences.push(current);
  });

https://jsfiddle.net/t6fL04cm/1/ https://jsfiddle.net/t6fL04cm/1/

About jQuery .is() method: https://api.jquery.com/is/ 关于jQuery .is()方法: https : //api.jquery.com/is/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM