views:

79

answers:

6

If I have valvo that obtain from database, How can I set volvo option status into active(checked) by using JQuery?

<select name="car">
      <option value="volvo">Volvo</option>
      <option value="saab">Saab</option>
      <option value="mercedes">Mercedes</option>
      <option value="audi">Audi</option>
</select>

I don't know how to manager control that have same identity.
??? $('input[name="car"]').attr('checked', true);

+4  A: 

Since your example is a drop down list you have to use val()

$("select[name='car']").val('volvo');

If you want to use radio button then you can use

$(":radio[value='volvo']").attr ( "checked" , true );

for the following HTML

<input type="radio" value="volvo" />
<input type="radio" value="saab" />
<input type="radio" value="mercedes" />
<input type="radio" value="audi" />
rahul
The title threw me off initially, too. I've updated the title (from radio button to dropdown list) to reflect the example. Unfortunately, this makes the first part of your answer irrelevant. Sorry.
tvanfosson
Yeah, I was also confused at first.
rahul
+1  A: 

Does JQuery support multiple CSS attribute selectors? If so, this should work:

$('input[name=car][value=volvo]').attr('checked', true);

Otherwise, you can always loop through all available radio buttons, check their value, and check them when the value matches.

Duroth
a) it's not an input, despite the title, the example shows a select. b) the value is on the option, not the select so you'd need to use a descendent selector
tvanfosson
+7  A: 

This also works:

$("select[name=car]").val('volvo');
Nick Craver
+2  A: 
$('select[name="car"]').val("volvo");

A select box is different to a radio button, it doesn't have a 'checked' attribute. The above works, although the specific attribute you want to set on the option element is selected:

$('select[name="car"]').attr("selected", "selected");
roryf
+1  A: 

This should work for radio buttons as stated on your original question.

$('input[name=car]:radio').attr('checked','checked');

This should work for select

$('select[name=car]').val('volvo');
Raúl Roa
+1  A: 

To set the drop down value as selected then it may help you. http://praveenbattula.blogspot.com/2009/08/jquery-how-to-set-value-in-drop-down-as.html

Rare Solutions