根据输入值选中的复选框

时间:2018-09-21 12:31:57

标签: jquery html5

我有四个复选框和类似的输入

<input type="text" value="" class=" windows ">

我有这个输入:1010

分裂后我有1, 0, 1, 0

我要检查输入是否为1,然后将复选框设置为选中,如果为0,则取消选中复选框。 我已经尝试过:

$(':checkbox').prop('checked', this.checked);

但是要选中所有复选框!
任何想法。

3 个答案:

答案 0 :(得分:1)

您可以遍历复选框,并根据1/0值对每个复选框进行检查/取消选中。

E.G:

<input type="checkbox" class="myCheckboxes" />
<input type="checkbox" class="myCheckboxes" />
<input type="checkbox" class="myCheckboxes" />
<input type="checkbox" class="myCheckboxes" />
<input type="checkbox" class="myCheckboxes" />

<script>
    var arrayFromInput = [ 1, 0, 1, 0 ];

    var checkBoxes = document.getElementsByClassName('myCheckboxes');

    for(var i=0; i<checkBoxes.length; i++)
    {
        if(i > arrayFromInput.length)
        {
            break;
        }

        checkBoxes[i].checked = arrayFromInput[i];
    }


</script>

答案 1 :(得分:1)

您可以使用prop's callback function

$(':checkbox').prop('checked', function(index) {
   return +yourArray[index] === 1;
});

答案 2 :(得分:0)

这应该可以解决问题。当输入的值的长度与复选框的数量相同时,它会根据输入的数字启用正确的复选框。

因为JavaScript中的数字0false,而其他数字是true,我们可以在for循环中说.checked = parseInt(val[i])

建议限制输入,以便最多可以输入4个字符,并且只能接受0和1。

$('.input-cb').on('input', function(){
  var val = $(this).val();
  if(val.length === $('.target-cb').length) {
    for(var i = 0; i < val.length; i++) {
      $('.target-cb').get(i).checked = parseInt(val[i]);
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="" class="windows input-cb">
<div id="cb-wrapper">
  <input type="checkbox" value="" class="windows target-cb">
  <input type="checkbox" value="" class="windows target-cb">
  <input type="checkbox" value="" class="windows target-cb">
  <input type="checkbox" value="" class="windows target-cb">
</div>