arma_best
arma_best

Reputation: 65

I can't check radio button using jquery

I have 2 radio buttons and I can't check them using jQuery ... What's wrong ?

HTML:

<table border="0">
<tr>
    <td style="width:85px;text-align:center;"><h4>Gender:</h4></td>
    <td style="width:85px;"><label><input type="radio" name="sex" value="male" id="maleradio" />Male</label></td>
    <td style="width:85px;"><label><input type="radio" name="sex" value="female" id="femaleradio"/>Female</label></td>
</tr>
</table>

jQuery:

 if (localStorage.getItem("gender") == "male") {
        console.log("Works fine");
        $("#maleradio").prop("checked", true);
    }

I get message "Works fine", but radio stay unchecked ...

Upvotes: 0

Views: 1566

Answers (2)

Kavin Kumar
Kavin Kumar

Reputation: 51

Give your Id value in #Id and execute the remaining statement.

$("#Id").prop("checked", true);       

To get the value of the radio button

$("#Id").is(":checked");   

If it is checked then it will return 'true' else 'false'

Upvotes: 0

Milind Anantwar
Milind Anantwar

Reputation: 82241

Use .prop() to set checked property:

jQuery("#maleradio").prop("checked", true);

Working Demo

Update: You need to make sure that dom element with id maleradio is loaded when above script is executed. You can ensure this by wrapping the script in document ready event.

Upvotes: 3

Related Questions