How to Check a Radio Button with jQuery

Radio buttons are an essential element in forms and surveys. They allow the user to select only one option from a list of choices.

In this Javascript tutorial, we will go over the steps to check a radio button with jQuery, the popular JavaScript library.

jQuery provides a simple and concise way to interact with HTML elements and perform actions such as checking a radio button.

To check a radio button using jQuery, we will use the prop() method.


Getting Started

Before we get into the code, make sure that you have included the latest version of jQuery in your HTML file.

You can download the library from the official jQuery website or link to it from a Content Delivery Network (CDN).

HTML Markup

Here is the HTML markup for the radio buttons we will be working with:

<form>
  <input type="radio" id="radio1" name="radio-group" value="Option 1">
  <label for="radio1">Option 1</label>
  <br>
  <input type="radio" id="radio2" name="radio-group" value="Option 2">
  <label for="radio2">Option 2</label>
  <br>
  <input type="radio" id="radio3" name="radio-group" value="Option 3">
  <label for="radio3">Option 3</label>
</form>

In the code above, we have created a form with three radio buttons.

Each radio button has a unique id and a shared name attribute.

The name attribute is used to group the radio buttons together, so only one can be selected at a time.

Checking a Radio Button with jQuery

To check a radio button with jQuery, we first need to select it.

We can do this by using the $() function and passing in the id of the radio button.

In this example, we will check the first radio button with the id of “radio1”.

$(document).ready(function() {
  $("#radio1").prop("checked", true);
});

In the code above, we have wrapped the code in the $(document).ready() function to ensure that the page has loaded before we interact with the radio buttons.

Inside the function, we use the $("#radio1") to select the first radio button and then use the prop("checked", true) method to check it.

That’s it! With just a few lines of code, you can easily check a radio button with jQuery.


Conclusion

In this tutorial, we went over the steps to check a radio button with jQuery.

We learned how to select the radio button using the $() function and the prop() method.

With this knowledge, you can now easily interact with radio buttons in your web projects and perform actions such as checking and unchecking them.