选中复选框时添加字符串

时间:2018-11-17 16:38:33

标签: jquery html arrays

我在页面上有复选框。我想做的是,当用户单击复选框时,其值将被打印在表格下方。可以一行打印多个值,并用','分隔: 像这样

  

a,b,c,d

function gant(id) {
  var arr = []
  $('#pil_' + id).each(function() {
    if ($(this).is(":checked")) {
      arr.push($(this).val())
    }
  })
  var vals = arr.join("+");
  var str = vals;
  $("#val").text(str);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label><input type="checkbox" name="selected" id="pil_1" onchange="gant(1)" value="a" />a</label>
<label><input type="checkbox" name="selected" id="pil_2" onchange="gant(2)" value="b"/>b</label>
<label><input type="checkbox" name="selected" id="pil_3" onchange="gant(3)" value="c" />c</label>
<label><input type="checkbox" name="selected" id="pil_4" onchange="gant(4)" value="d"/>d</label>
<div id="val"></div>

但是它仅显示a或b或c或d

3 个答案:

答案 0 :(得分:2)

将只有一个id传递给函数,因此请遍历该类。

$('.offers:checked').each(function(){
     arr.push($(this).val());          
})

答案 1 :(得分:0)

下面应该可以工作

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function gant(id) {

var arr = [];
  $(':checkbox[name="selected"]').each(function() {
    if ($(this).is(":checked")) {
        arr.push($(this).val())
    }

  })
  //alert(arr);
  var vals = arr.join(",");
  var str = vals ;
  $("#val").text(str);
}
</script>
</head>
<body>

<label><input type="checkbox" name="selected" id="pil_1" onchange="gant(1)" value="a" />a</label>
<label><input type="checkbox" name="selected" id="pil_2" onchange="gant(2)" value="b"/>b</label>
<label><input type="checkbox" name="selected" id="pil_3" onchange="gant(3)" value="c" />c</label>
<label><input type="checkbox" name="selected" id="pil_4" onchange="gant(4)" value="d"/>d</label>
<div id="val"></div>
</body>
</html>

答案 2 :(得分:-1)

只需将id选择器更改为此类,即可:

function gant(id){
            var arr = [];
            $('.offers').each(function(){
                if($(this).is(":checked")){
                    arr.push($(this).val())
                }
            })
            var vals = arr.join(",");
            var str = vals;
            $("#val").text(str);
            }
        
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<label><input type="checkbox" name="selected1" id="pil_1" onChange="gant(1)" value="a" class="offers" />a</label>
        <label><input type="checkbox" name="selected2" id="pil_2" onChange="gant(2)" value="b" class="offers" />b</label>
        <label><input type="checkbox" name="selected3" id="pil_3" onChange="gant(3)" value="c" class="offers" />c</label>
        <label><input type="checkbox" name="selected4" id="pil_4" onChange="gant(4)" value="d" class="offers" />d</label>
        <br>
        <label id="val"></label>