79
votes

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.

4
Are you sure value="car" and the text is 1, and not the other way around? Is the <select> code static, or dynamically created from something like a database? - freefaller
You want to select this with the serverside? Why no serverside tag? - epascarello

4 Answers

121
votes

You can select the value using javascript:

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

DEMO

38
votes

If you are using jQuery:

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

try out this....

JSFIDDEL DEMO

using javascript

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

using jQuery

$('#sel').val('car');
1
votes
document.getElementById('drpSelectSourceLibrary').value = 'Seven';