How can I know which radio button is selected via jQuery?

Learn, how to check which radio button is selected or not using jQuery?
Submitted by Pratishtha Saxena, on May 08, 2022

To know the value of the selected radio button, here we are going to use the "checked" selector of jQuery.

The checked selector selects all the checked checkboxes or radio buttons.

Syntax:

$('input[type="radio"]: checked')

Note: Always remember to apply the jQuery CDN link before writing the function.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

Let's create a function and store the value of the checked radio button in a variable called res. Now, if the length of res is greater than 0, then we have some value in that variable and we'll print it. Else, if the variable is empty then no value has been selected.

For better understanding go through the code given below:

<script>
    $(document).ready(function(){
        $('#myform').click(function(){
           var res = $('input[type="radio"]:checked');

           if(res.length>0){
                $('#divResult').html(res.val() + ' is checked.');
           }
           else{
                 $('#divResult').html('No radio button checked.');
           }
        });
    });
</script>

HTML Code:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Title</title>
  </head>
  <body>
    <form id="myform">
      <input type="radio" name="country" value="India" />India
      <br />

      <input type="radio" name="country" value="England" />England
      <br />

      <input type="radio" name="country" value="USA" />USA <br /><br />

      <div id="divResult"></div>
    </form>
  </body>
</html>

Output:

Radio button is selected via jQuery





All jQuery Examples

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.