Javascript / Jquery solution neede for select box

I have a html select box.

I have a option key in a javascript variable.

I want to update html select box if the key matches to any of the options in the html select box. I need a javascript/jquery solution to do this.


I have inputs as …

HTML select box
<select name=“something” id=“selectedCar”>
<option value=“1”>Volvo</option>
<option value=“2” selected=“selected”>Saab</option>
<option value=“3”>Mercedes</option>
<option value=“4”>Audi</option>

Javascript variable

var selectKey=“4”;

I want output as …

Output HTML

<select name=“something” id=“selectedCar”>
<option value=“1”>Volvo</option>
<option value=“2”>Saab</option>
<option value=“3”>Mercedes</option>
<option value=“4” selected=“selected”>Audi</option>

I need a javascript / Jquery solution to achieve this . Do you have a solution to this problem ?

Something like this should do it.

$('select[name="something"] option[value="' + selectKey + '"]').attr('selected', 'selected');

Instead of name can I use id ?

I am trying to do this …

$(‘select[id=“selectedCar”] option[value="’ + selectKey + ‘"]’).attr(‘selected’, ‘selected’);

Does id selector work this way ? If not whats the correct syntax ?


you mean this syntax…

$(‘#selectedCar’ option[value=“’ + selectKey + '”]').attr(‘selected’, ‘selected’);

Nearly, you have an additional single quote in there that’s messing things up.

Nearly, you have an additional single quote in there that’s messing things up.

I guess then …

$(‘#selectedCar option[value="’ + selectKey + ‘"]’).attr(‘selected’, ‘selected’);

Is this correct ?

I like this actually though…

$(“#selectedCar option[value='” + selectKey + “']”).attr(‘selected’, ‘selected’);

The difficulty with that second one is that it’s mixing up what the quotes are used for. Double quotes are accepted use for HTML attribute values, whereas single quotes are the accepted ones to use in JavaScript for strings, to help reduce confusion between the two.

Nothing’s stopping you from using one or the other, but consistency goes a long way.

Excellent. Thanks. You are very much helpful.

I’ll test this in the system . If I find anything wrong I’ll get back to you.

I have tested in the system . It does not put selected attribute.

Are you sure this code works ? Can we set attribute of option this way using jquery ?

Of course it does. Here’s some sample code that demonstrates this for you.

Awesome. This works fine. You are very much helpful.

Do you know html.
Can you help with this html ?