HTML SELECT - Change selected option by VALUE using JavaScript

JavascriptHtmlHtml Select

Javascript Problem Overview


There can be many options in a SELECT dropdown.

<select id="sel">
    <option value="car">1</option>
    <option value="bike">2</option>
    <option value="cycle">3</option>
    ...
</select>

I'm creating a Update Profile page where a user's profile is retrieved from the database and a form is shown with those values. When it comes to SELECTdropdown, there are many options. So, its tedious test all values

if (value == '1')
    echo "<option selected value='car'>1</option>";`

So, I want to have the corresponding option selected from its value. Like when I do something like sel.value = 'bike' using JavaScript the option 2 should be selected.

Javascript Solutions


Solution 1 - Javascript

You can select the value using javascript:

document.getElementById('sel').value = 'bike';

DEMO

Solution 2 - Javascript

If you are using jQuery:

$('#sel').val('bike');

Solution 3 - Javascript

try out this....

JSFIDDEL DEMO

using javascript

​document.getElementById('sel').value = 'car';​​​​​​​​​​

using jQuery

$('#sel').val('car');

Solution 4 - Javascript

document.getElementById('drpSelectSourceLibrary').value = 'Seven';

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDilip Raj BaralView Question on Stackoverflow
Solution 1 - JavascriptMichal KloudaView Answer on Stackoverflow
Solution 2 - JavascriptTrevorView Answer on Stackoverflow
Solution 3 - JavascriptVijayView Answer on Stackoverflow
Solution 4 - Javascriptuser5846985View Answer on Stackoverflow