简体   繁体   中英

JQuery: Check if any radio button is checked using radio button class name

I realize similar question had earlier been answered on stack overflow a few times. I checked all the questions and none were similar to mine.

I have a html form that has some radio buttons. In my validation I want to check if atleast one of the radio buttons are checked.

My approach so far:

  • All radio buttons have same class
  • All radio buttons have same name

I need to

  • check if atleast one of the radio button is selecetd
  • read the value of selected button.

My Javascript so far

function supportFormValidation(){
   var isChecked = $('.radioButton').attr('checked')?true:false;
   alert(isChecked);
   return false;}    

This always returns false. But when I try to read vale by individual IDs of each radio button it returns true. Is there any way I can check if a radio button is checked by using the class name.

JSFiddle: http://jsfiddle.net/evj9nch3/

只需使用:checked。

var isChecked = !!($('.radioButton:checked').length);

In order to access the checked property you need to use the prop function (after 1.6 anyways). Because the value is either true or false, it's considered a property of the element not an attribute.

Nits answer is a better way of doing it, but look below for the reason why your implementation isn't working.

Take a look at this post for more info

Here is a link to the fiddle

 function supportFormValidation() { var isChecked = $('.radioButton').prop('checked') ? true : false; alert(isChecked); return false; }; supportFormValidation(); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type='checkbox' class='radioButton' checked='true' /> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM