How to Get Selected Radio Button Value in Jquery?

November 4, 2021
Jquery
How to Get Selected Radio Button Value in Jquery?

In this tutorial, you will learn how to get the selected radio button value in jquery.

This is one of the common things to do when we get the values of the form fields and getting the selected radio value is most likely you can encounter with.

We are covering different cases in which we will get the value of selected radio using class and then on change event in jquery.

Let’s get started.

Step 1: HTML Boilerplate Template:

This is the boilerplate template we are starting with, in which we have html, body tags created and have alsoincluded jquery.

<html>
  <body>
  </body>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

</html>

Step 2: Creating the Radio Button

Now Let’s create the radio buttons in the body tag.

<input type="radio" name="food" class="food" value="pizza"> Pizza
<input type="radio" name="food" class="food" value="burger"> Burger

Step 3: Get the value of the radio button

In this section, we will now get the value of the radio button using class. We are using :checked to get the value of the selected radio button. You can add the following code before the closing tag of body tag.

<script>
  let radio_value=$(".food:checked").val();
  console.log(radio_value);
</script>

Bonus: Get the value of the radio button on the change event

In this section, we will now get the value of the radio button on the change of the radio button selection. You can add the following code before the closing tag of the body tag.

<script>

    $(".food").change(function(){
      let radio_value=$(".food:checked").val();
      console.log(radio_value);
    });
</script>

Conclusion:

Hope you have learned today how to get selected radio button value in Jquery using the class and on change event.

Let me know if you have any questions in the comments.

See you in the next one.

Write a Reply or Comment

Your email address will not be published. Required fields are marked *


Icon