Reputation: 67
i have four check-boxes and an input like that
<input type="text" value="" class=" windows ">
i have this input: 1010
after splitting i have 1, 0, 1, 0
i want to check if input is 1 then set checkbox checked, when 0 set the checkboxes unchecked. i have tried this:
$(':checkbox').prop('checked', this.checked);
but that making all checkboxes checked!
any ideas please.
Upvotes: 1
Views: 327
Reputation: 144689
You could use the prop
's callback function:
$(':checkbox').prop('checked', function(index) {
return +yourArray[index] === 1;
});
Upvotes: 1
Reputation: 13222
This should do the trick. When the length of the value of the input is the same as the amount of checkboxes it enables the right ones based on the inputted number.
Because the number 0
is false
in javascript and other numbers are true
we can say .checked = parseInt(val[i])
inside the for loop.
It is advised to restrict the input so not more then 4 characters can be typed and only 0 and 1 are accepted.
$('.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>
Upvotes: 0
Reputation: 1590
You can iterate through the checkboxes and check/uncheck each one based on the 1/0 value.
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>
Upvotes: 1