I have a set of radio buttons. I am trying to put a validation that if none of the radio buttons are checked I need to show an error message. Is there开发者_开发问答 a way to get a collective value of the radio buttons? Or will I have to iterate each radio button?
You can try this
if($("containerOfRadioButtons").find("input:radio:checked").length)
{
alert("Error message");
}
If you want to get the value of radiobuttons in Javascript, looping through them is the most straightforward solution. You could assign one of them to be selected by default and that would make sure that at least the default value is selected, since you can't deselect a radio button manually (via console, yes, but that's a whole different story)
You can match all the checked radio buttons with the :radio and :checked selectors:
if (!$("input:radio:checked").length) {
alert("None of the radio buttons are checked.");
}
精彩评论