Reputation: 1437
I have this set of radio buttons, let's say
radio 1
radio 2
radio 3
radio 4
and a checkbox;
checkbox 1
What I wanted to achieve is when I click either radio 1 or radio 3 the checkbox 1 will be checked. If the checkbox is checked and when you click either radio 2 or radio 4, the checkbox will be unchecked.
I already implemented some code for it, but it has this glitch that when I click radio 1 it'll check the checkbox, but when I click radio 3 it'll uncheck the checkbox.
Well supposedly, when I click radio 1 it'll check and even if I'll click radio 3, it shouldn't uncheck the checkbox.
here's my code:
jQuery('#radio1 input:radio, #radio3 input:radio').click(function(){
var checkbox = jQuery('#checkbox1');
checkbox.attr('checked', !checkbox.attr('checked'));
});
Upvotes: 4
Views: 8806
Reputation:
$('input[type="radio"]').click(function(){
var checkbox = $('#checkbox1');
switch(this.id){
case 'radio1':
case 'radio3':
checkbox.attr('checked', true);
break;
case 'radio2':
case 'radio4':
checkbox.attr('checked', false);
break;
}
});
Upvotes: 2
Reputation: 150263
jQuery('#radio1, #radio3').click(function(){
jQuery('#checkbox1').prop('checked', true);
});
jQuery('#radio2, #radio4').click(function(){
jQuery('#checkbox1').prop('checked', false);
});
Though you can do it in many other ways. One more example:
jQuery(':radio').change(function(){
var toCheck = this.id == 'radio1' || this.id == 'radio3';
jQuery('#checkbox1').prop('checked', toCheck);
});
Demo (markup was taken from @Matrix)
Upvotes: 1
Reputation: 20313
HTML CODE:
Radio1 :<input type="radio" id="radio1" name="radio"/><br>
Radio2 :<input type="radio" id="radio2" name="radio"/><br>
Radio3 :<input type="radio" id="radio3" name="radio"/><br>
Radio4 :<input type="radio" id="radio4" name="radio"/><br>
Checkbox :<input type="checkbox" id="checkbox1"/>
jQuery CODE:
jQuery('#radio1 , #radio3').click(function(){
jQuery('#checkbox1').attr('checked', true);
});
jQuery('#radio2 , #radio4').click(function(){
jQuery('#checkbox1').attr('checked', false);
});
Live DEMO:
Upvotes: 3