Reputation: 25
jQuery newbie, here. I can't get this to work. This is what I'm using to disable a radio button based on a previous radio button.
$('document').ready(function() {
$('input[name="a"]').change(function() {
if($(this).val() == '1') {
$('input[name="b"]').removeAttr('disabled');
} else {
$('input[name="b"][value="1"]').attr('disabled','disabled');
}
});
});
and:
<input type="radio" name="a" value="1" /> A-1
<input type="radio" name="a" value="2" /> A-2
<input type="radio" name="b" value="1" /> B-1
<input type="radio" name="b" value="2" /> B-2
So if I checked A-2, B-1 gets disabled. But say I had B-1 checked to begin with, and then I checked A-2, then I'd want B-1 to get unchecked. I've tried adding this in:
if($('input[name="b"][value="1"]').is(':disabled')) {
$('input[name="b"][value="1"]').removeAttr('checked');
}
It does the job, but it also unchecks B-2 if I had that checked first. I only want B-1 to get unchecked. (I hope this makes sense.)
What am I doing wrong?
Upvotes: 0
Views: 2275
Reputation: 3775
$('input[name="a"]').change(function () {
var $b = $('input[name="b"]');
if (this.value == 1) {
$b.removeAttr('disabled');
}
else {
$('input[name="b"][value="1"]:checked').removeAttr('checked'); // the selector behavior is funky here...
$b.attr('disabled', true);
}
});
this works as you want.
there is an issue with the [value="1"] selector thou (when used without :checked), smells like a jquery bug. But don't worry about it ;)
and a little fiddle for you ^^
Upvotes: 1
Reputation: 719
I had to learn something like that in a hurry in the past: the trick is make a family of radio buttons:
family NAME
child ID0
child ID1
child IDn
In you specific case, you might be looking for something like this (gender):
<input type="radio" name="gender" id='male' value="M" > Male
<input type="radio" name="gender" id='female' value"F" > Female
And, for instance, likes:
<input type="radio" name="likes" id='tv' value="TV" > Watchs TV
<input type="radio" name="likes" id='radio' value="radio" > Listens to Radio
When you have a FAMILY of radio buttons, once one is clicked, the other is unclicked automatically.
Then you can check either by just
$('#male').is(':checked') .... $('#female').is(':checked') .....
And, you can, also, start any of them disabled or not or disable the other by clicking this: $('#male').click();
Upvotes: 0