开发者

jQuery - Error on if none of the radio button is checked

开发者 https://www.devze.com 2023-03-23 13:53 出处:网络
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

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.");
}
0

精彩评论

暂无评论...
验证码 换一张
取 消