Reputation: 2780
So I'm busy on a registration, and I want people to choose their gender. I do this by the use of radio buttons. Now, what I want, is to have a disabled post
button untill one of the two boxes is selected, this I do with jQuery:
var $radio = $("input:radio");
$radio.change(function()
{
var checkedButtons = false;
$radio.each(function() {
if (this.checked)
{
var checkedButtons = true;
return false;
}
});
if (checkedButtons)
{
$("#postGender").removeAttr("disabled");
}
else
{
$("#postGender").attr("disabled", "disabled");
}
});
This little piece is code, was found by me on stackoverflow. The only thing wrong is that it doesn't work.
See this for more code and ofcouse a demo: JsFiddle
Upvotes: 3
Views: 11649
Reputation: 14310
Something like this should do:
var $radio = $("input:radio");
$radio.change(function () {
if ($radio.filter(':checked').length > 0) {
$("#postGender").removeAttr("disabled");
} else {
$("#postGender").attr("disabled", "disabled");
}
});
http://jsfiddle.net/n6sta3dp/8/
A few sidenotes:
Upvotes: 0
Reputation: 12367
You can simplify this greatly.
If you think about it, once they click on a radio button, they can't really deselect it: they can only click on another radio button. So, once the button has changed once, there's really no need to monitor it anymore and you can just enable the button from there.
$("input:radio").change(function () {
$("#postGender").attr("disabled", false);
});
Upvotes: 1
Reputation: 55569
Remove the var
within the first if
block. var checkedButtons = true;
is creating a different checkedButtons
within the scope of that block. So the first checkedButtons
will be unchanged, and the other is gone once the if
block is finished.
It should just be checkedButtons = true;
Upvotes: 1
Reputation: 207901
You could reduce all that to one line:
$("input:radio").change(function () {$("#postGender").prop("disabled", false);});
Upvotes: 12