Gideon Gideon - 3 years ago 171
HTML Question

Dynamically checked radio button, based on 'value' attribute, not checking

Trying to get a form to load pages with the previously checked radios already checked (upon a fresh load).

The submissions of that page are held as php variables which I can pass into the javascript, the rest should be simple, but it's not working for me.

My code:

<div class="question">
<label for="sv_213">Question?</label>


My javascript:

$(function() {
var $213 = Yes;
$("input[name='sv_213'][value="$213"]").attr('checked', true);


In the above js the

var $213 = <dynamically generated content>

Such that it is set equal to the value of the radio button that was checked

Here is a js fiddle with it not working:

Many thanks for any help.

Incidentally my code is based on this, previously asked question:
Set selected radio from radio group with a value

Answer Source

You need quotes around your value "Yes", since this is a string, and not a boolean or number.

var $213 = "Yes";

Also, you need to add the variable into the selector with +'s like this:

$("input[name=sv_213][value="+$213+"]").attr('checked', true);

Updated fiddle, working:

Full js code:

$(function() {
    var $213 = "Yes";
    $("input[name=sv_213][value="+$213+"]").attr('checked', true);


Update:## Since jQuery 1.6, you can also use the .prop method with a boolean value (this should be the preferred method):

$("input[name=sv_213][value="+$213+"]").prop('checked', true);

in my case, the .attr() method didnt worked for dynamically selecting the radio button whereas .prop() did.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download