How To Checked Radio Button In Jquery

In this blog post, we will learn how to check a radio button using jQuery. Radio buttons are a common HTML element used to allow users to select a single option from a group of options. When it comes to manipulating or interacting with radio buttons using JavaScript or jQuery, it can be a little tricky due to their unique behavior.

Prerequisites

Before we dive into the solution, make sure you have the following in place:

  • Basic understanding of HTML, CSS and JavaScript
  • Basic understanding of jQuery and how to include it in your project

HTML Markup

Let’s create a simple HTML form with radio buttons:

    <form>
        <label>
            <input type="radio" name="gender" value="male">
            Male
        </label>
        <label>
            <input type="radio" name="gender" value="female">
            Female
        </label>
        <label>
            <input type="radio" name="gender" value="other">
            Other
        </label>
    </form>
    

Checking a Radio Button Using jQuery

To check a radio button using jQuery, you can use the .prop() method. In the example below, we will check the “Male” radio button:

    $(document).ready(function() {
        $('input[type=radio][name=gender][value=male]').prop('checked', true);
    });
    

In this example, we first select the radio button with the name “gender” and the value “male”. Then, we use the .prop() method to set the “checked” property to true.

Checking a Radio Button Based on a Condition

If you want to check a radio button based on a specific condition, you can use an if statement along with the .prop() method. In the example below, we will check the radio button based on the user’s choice:

    $(document).ready(function() {
        var userChoice = "female";

        if (userChoice === "male") {
            $('input[type=radio][name=gender][value=male]').prop('checked', true);
        } else if (userChoice === "female") {
            $('input[type=radio][name=gender][value=female]').prop('checked', true);
        } else {
            $('input[type=radio][name=gender][value=other]').prop('checked', true);
        }
    });
    

In this example, we first define a variable named userChoice which contains a string value. Based on this value, we check the corresponding radio button using the .prop() method.

Conclusion

In this blog post, we learned how to check a radio button using jQuery. The .prop() method makes it easy to manipulate the “checked” property of radio buttons. Remember to first select the desired radio button with the appropriate name and value attributes before using the .prop() method.