sushibrain
sushibrain

Reputation: 2780

Disable button until one radio button is clicked

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

Answers (4)

Pevara
Pevara

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:

  • Once a radio button has been checked, it can never be unchecked by the user (unless he starts using the js console). I think it would be safe to remove the 'else' part in your function.
  • Don't forget that a form can also be submitted by using the enter key, so just disabling the button will not be enough. You should probably listen for the submit event of your form as well and check if the user made a choice before letting the submit go trough.

Upvotes: 0

AstroCB
AstroCB

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);
});

Demo

Upvotes: 1

Michael Zajac
Michael Zajac

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

j08691
j08691

Reputation: 207901

You could reduce all that to one line:

$("input:radio").change(function () {$("#postGender").prop("disabled", false);});

jsFiddle example

Upvotes: 12

Related Questions