Get selected radio button value using jquery

Selected Radio Button Value

You can easily get selected radio button value using jQuery. However you can also done this with Javascript or any programming language, but you have to write dozens lines of code which is time consuming to execute.

$('.rdoNumber:checked').val();
// it return the vlaue of Selected Radio Button
// If no one radio button is selected then it return undefined

Check if radio button is selected or checked

$('.rdoNumber').is(':checked');
// return True if any Radio Button is selected otherwise it return False

Remove selected radio button

$('.rdoNumber').prop('checked', false);
// It uncheck the selected radio button

CODE
<!DOCTYPE html>
<html>
<head>
  <title>jQuery With Example</title>
  <script src="http://code.jquery.com/jquery-1.9.1.js" type="text/javascript"></script>
  <script type="text/javascript">
    $(function () {
      $('#btnGetSelected').click(function () {
        alert($('.rdoNumber:checked').val());
      });

      $('#btnValidation').click(function () {
        if ($('.rdoNumber').is(':checked')) {
          alert("True")
        }
        else {
          alert("False")
        }
      });

      $('#btnRemove').click(function () {
        $('.rdoNumber').prop('checked', false);
      });

    });
  </script>
</head>
<body>
  <div>
    <input type="radio" class="rdoNumber" name="Number" value="1" />One<br />
    <input type="radio" class="rdoNumber" name="Number" value="2" />Two<br />
    <input type="radio" class="rdoNumber" name="Number" value="3" />Three<br />
  </div>
  <button id="btnGetSelected">GetSelected</button>
  <button id="btnValidation">Validation</button>
  <button id="btnRemove">Remove</button>
</body>
</html>
DISPLAY
One
Two
Three

3 comments :

  1. Thankyou so much for this, I have been trawling through countless hours of stackoverflow examples to no avail, finally found an example that does the job. Cheers again.

    ReplyDelete
  2. i am generating dynamic radio boxes and i have given input name as Arr[$index][$optn] how can i validate these checkboxes with javascript

    ReplyDelete
    Replies
    1. Hi Divya,
      You are creating radiobox with different name.
      Firstly create radio boxed with same name with different value or different attribute.
      Suppose you create two radio boxed like:
      <input type="radio" class="rdoGender" name="Gender" value="Male" /> Male
      <input type="radio" name="rdoGender" value="Female" /> Female

      To validate in jQuery:
      if($('.rdoGender').is(':checked'))
      {
      //your code
      }


      But to validate in JavaScript:

      var isValid = false;
      var el = document.getElementsByTagName('input');
      for (var n = 0; n < elements.length; n++) {
      if (el[n].type == 'radio' && el[n].name == 'Gender' && el[n].checked) {
      isValid = true;
      }
      }
      if(isValid)
      {
      //your code
      }

      Delete