0

I have 3 checkboxes with different id, Checkbox1, checkbox2 and checkbox3. how i can make checkbox 3 automatically checked if checkbox1 & checkbox2 is checked.

html

<input type="checkbox" class="check" id="checkbox1">
<input type="checkbox" class="check" id="checkbox2">
<input type="checkbox" class="check" id="checkbox3">

jquery

var x = $("#checkbox1").is(':checked');
var y = $("#checkbox2").is(':checked');
if(x && y) {
document.getElementById("checkbox3").is(':checked');} 
else {document.getElementById("checkbox3").checked = false;
}
4
  • Bind change event on C1 & C2 and in handler check if both are checked, if yes then check C3 else uncheck C3. Commented Feb 13, 2017 at 2:49
  • can you give an example for bind checking 2 event C1 & C2 ? @Tushar Commented Feb 13, 2017 at 2:53
  • Demo Commented Feb 13, 2017 at 2:53
  • lol, that is so simple. thankyou so much @Tushar Commented Feb 13, 2017 at 2:58

2 Answers 2

0

Firstly, check you code :D

var y = $("#checkbox2").is('checked');

should be:

var y = $("#checkbox2").is(':checked');

You can do:

<script>
$(document).ready(function () {
    $('.check').on('change',function() {
        var x = $("#checkbox1").is(':checked');
        var y = $("#checkbox2").is(':checked');
        $('#checkbox3').prop('checked',(x && y));
    });
});
</script>

hope this help ^^

Sign up to request clarification or add additional context in comments.

3 Comments

lol, i'm sure i just write it wrong in that post but in my code it was right.. anyway, thankyou it works like a charm.. :) just for note, answer from @Tushar is also correct.
For checkboxes I generally recommend using a click event rather than change, because in certain older browsers if you "click" the checkbox with the keyboard the change event isn't triggered until tabbing off it, whereas the click event is triggered immediately (even from the keyboard).
sure :) we can add more binding events e.g. .on('click change',function() { ... });
0

I think maybe this will work, I am not 100% sure, but here:

var x = $("#checkbox1").is(':checked');
var y = $("#checkbox2").is('checked');
var z = $("#checkbox3").is('checked');
if(x && y && z) {
document.getElementById("checkbox3").is(':checked');} 
else {document.getElementById("checkbox3").checked = false;
}

1 Comment

document.getElementById("checkbox3").is(':checked') - That won't work. DOM elements don't have an .is() method, and in any case having that line in the if block wouldn't do anything.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.