How To Make Radio Button Checked In Jquery

In this tutorial, we will learn how to make a radio button checked using jQuery. Radio buttons are commonly used in forms when there is a need to choose one option among several options. We can easily manipulate the state of radio buttons using jQuery.

Getting Started

First, make sure you have included the jQuery library in your project. You can include it using the following script tag:

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

HTML Structure

Let’s create a simple form with three 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>
    

Make Radio Button Checked

We can make a radio button checked by setting its ‘checked’ property to true. The following code makes the radio button with the value “female” checked:

<script>
    $('input[type=radio][value=female]').prop('checked', true);
</script>
    

Example

Combining everything together, our complete code will look like this:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>How to Make Radio Button Checked in jQuery</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>

<body>
    <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>

    <script>
        $('input[type=radio][value=female]').prop('checked', true);
    </script>
</body>

</html>
    

With this code, the “female” radio button will be checked by default when the page loads. You can change the value in the jQuery selector to make a different radio button checked.

Conclusion

Now you know how to make a radio button checked using jQuery. This simple technique can be helpful when you want to set a default option or manipulate radio buttons based on user input. Happy coding!