0

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/

user3861559
  • 973
  • 8
  • 25
  • 43

3 Answers3

2

Just use :checked.

var isChecked = !!($('.radioButton:checked').length);
Etheryte
  • 24,589
  • 11
  • 71
  • 116
1

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' />
Community
  • 1
  • 1
Kevin
  • 2,752
  • 1
  • 24
  • 46
0

You can use this. I checked this is working

$(".ClassName").prop("checked", true)