user3128861
user3128861

Reputation: 121

Give a condition to auto check the checkbox

is there a way to do in javascript such that if I check a few checkboxes as a condition, one of the checkbox will be check. Currently here's my logic for the codes but it cant work.

$(document).ready( function a()
{
   if (  $('#condition1' && $('#condition2').is(':checked'))
    {
       $('#checkbox1').attr('checked', true);
    }
});

Also, is it possible to put a class in the checkbox to do the check function instead of id?

Upvotes: 0

Views: 1914

Answers (2)

Desmond Liang
Desmond Liang

Reputation: 2310

You script is executed on document ready. After the execution is won't react to any action you take. In order to accomplish what you want, you need to run the script every time a check box is clicked.

$(document).ready( function(){
$('input[type="checkbox"]').click(function(){
    if ( $('#condition1').is(':checked') && $('#condition2').is(':checked')){
       $('#checkbox1').prop('checked', true);
    }else{
       $('#checkbox1').prop('checked', false);
    }
});

});

http://jsfiddle.net/CaZ7j

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

Your need to use a change handler

jQuery(function ($) {
    var $checks = $('#condition1, #condition2').change(function () {
        $('#checkbox1').prop('checked', $checks.is(':checked'));
    })
});

Demo: Fiddle

Upvotes: 1

Related Questions