How to set a drop-down list to a specific value

If I have valvo that get from the database, How to set the status of the volvo option to active (marked) 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 do not know how to manage a manager with the same identity.
??? $('input[name="car"]').attr('checked', true);

+3
source share
5 answers

Since your example is a dropdown, you should use val ()

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

If you want to use the radio button, you can use

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

for the next HTML

<input type="radio" value="volvo" />
<input type="radio" value="saab" />
<input type="radio" value="mercedes" />
<input type="radio" value="audi" />
+5
source

This also works:

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

, 'checked'. , , option, selected:

$('select[name="car"]').attr("selected", "selected");
+2
source

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

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

Otherwise, you can always scroll through all available switches, check their value and check them when the value matches.

+1
source

This should work for the switches as stated in the original question.

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

This should work for selection.

$('select[name=car]').val('volvo');
+1
source

Source: https://habr.com/ru/post/1732847/


All Articles