views:

53

answers:

1

I have this HTML code for radios:

<input type='radio' name='a_27' value='Yes' id='a_27_0' />

<input type='radio' name='a_27' value='No' id='a_27_1' />

I'm trying to set the selected value of the radio using this code:

var field="a_" + this.id;
$('[name="' + field + '"]').val(this.value);
console.log("name is " + field + ", val is " + this.value);

However it doesn't work, nothing happens when this runs. Here's the output from Firebug's console which occurs after the 3rd line:

name is a_27, val is Yes

Any ideas?

I would prefer a method which would also work on <select>s, so I wouldn't need to write additional/seperate code for radios and selects.

Edit: A weird problem I've noticed that although my html code gives a different value (yes/no), in firebug it shows both radios as having the value 'yes'. If I select no and click save, the javascript function still receives 'yes' instead of no. Am I doing something wrong?

Edit 2: The full function:

function processMultiOptAnswers()
{
    $.each(multiOpts,function()
        {
            var field="a_" + this.id;
            console.log("name is " + field + ", val is " + this.value);

            $('[name="' + field + '"]').val(this.value);
        }
    );
}
A: 

your log should be if this.value is different.

$('[name="' + field + '"]').val(this.value);
console.log("name is " + field + ", val is " + $('[name="' + field + '"]').val());

To make it selected

$('[name="' + field + '"]').attr("checked", "checked");

I haven't tested this, but you might have to remove that attribute from the other ones.

Daniel A. White
Weird, that does give the new (changed) value but on the form itself the appropriate value isn't selected. Is there something wrong with my html code for creating the radios?
Click Upvote
See my edit above
Click Upvote
That made the radio get selected but its still showing the same value for all radios...
Click Upvote
Your selector should use ID rather than the NAME to slect your radios as they ALL share the same name - you're updating all of them to the new value at once.
sanchothefat
Is there no way to select the radio I want without knowing the id of the radio?
Click Upvote
For example, if I wanted to select the radio saying 'No' but I didn't know the id of it, how can I select it? (Dan, I unchecked your answer because by using name=.. its updating values of both radios instead of selecting the one whose value is 'Yes'
Click Upvote
Maybe what you can do is add a new radio item with the new value, then remove the ones with the value you want to replace.
Daniel A. White