tags:

views:

50

answers:

1

I want to check is there any radio button selected and if there is no selection to print some alert message.

The html code is:

<form action="" id="form" name="form" method="post">
<input type="radio" id="form_rd" name="form_rd" value="1"> 1
<input type="radio" id="form_rd" name="form_rd" value="2"> 2
<input type="radio" id="form_rd" name="form_rd" value="3"> 3
<button type="submit">send</button>
</form>

Jquery that I'm using for checking:

$("form#form").submit(function() {
if (!$("#form_rd").attr('checked')) {alert("not checked");return false;}
})

This jquery code is not working. What is the better solution for this radio button check?

+4  A: 

I cannot emphasize enough that IDs must be unique! So change your id="form_rd" into (for example) class="form_rd". Leave name alone, however, because the receiving end won't like the request if you change that too.

Try

$("form#form").submit(function() {
    if ($("#form :radio:checked").length == 0) {
        alert("not checked");
        return false;
    }
});

This will fail if you have multiple groups. Do you need a solution for that?

MvanGeest
@MvanGeest - Thanks. I tried with this but keep getting alert message "not checked" even if the radio button is checked?!
Sergio
Well, your form's ID is `form`, so I corrected that in the example. Try again. If it still doesn't work, show us some more HTML. (Or do you have multiple forms? All with the ID `form`? Then that's the problem.)
MvanGeest
@MvanGeest - Here is the example link:http://jsfiddle.net/4kEqx/I don't have multiple forms. Just one.
Sergio
This works: http://jsfiddle.net/HVJpZ/ (the error you see means that the form was submitted) I messed up the jsFiddle history, sorry for that.
MvanGeest
@MvanGeest - Thanks. Now it's working fine.
Sergio
If this answered your question, could you accept the answer? (Not that there's currently another answer that could confuse future visitors, but still.)
MvanGeest