85

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.

Dilip Raj Baral
  • 3,243
  • 6
  • 33
  • 60
  • 3
    Are you sure `value="car"` and the text is `1`, and not the other way around? Is the ` – freefaller Sep 04 '12 at 14:28
  • You want to select this with the serverside? Why no serverside tag? – epascarello Sep 04 '12 at 14:30

4 Answers4

128

You can select the value using javascript:

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

DEMO

Dave Chen
  • 10,762
  • 8
  • 38
  • 67
Michal Klouda
  • 13,903
  • 7
  • 51
  • 74
  • 3
    Remember: you may use sel.value = 'bike' instead of document.getElementById('sel').value – Eduardo Xavier Feb 09 '15 at 18:20
  • 2
    @EduardoXavier, if you first run 'var sel = document.getElementById('sel');', then yes, you can. Otherwise, no, you can't. If the element only has `id`, the only way is to get the element first. However, if it has the `name` attribute and it is inside a form, you can use `formelement.sel.value`. http://www.w3.org/TR/html5/forms.html#the-form-element and http://www.w3.org/TR/html5/forms.html#dom-form-nameditem – Denilson Sá Maia May 22 '15 at 18:46
  • 3
    @DenilsonSá This question is about the use of the "id". What you said about form and names is rigth but you're completly wrong when you say I can't access an element in the way I proposed. Let us do some practice then, have a look at here https://jsfiddle.net/tub6f0Lg/ :P cheers! – Eduardo Xavier Aug 04 '15 at 08:48
  • 1
    @EduardoXavier: I stand corrected, you are right! Thanks for pointing it out! :) http://www.w3.org/TR/html5/browsers.html#named-access-on-the-window-object However, although handy, relying on IDs being available as global variables because of window object may lead to messy and unreadable code. Consider another developer (maybe even yourself after a while) reading the code. – Denilson Sá Maia Aug 04 '15 at 23:52
  • http://javascriptstutorial.com/blog/selecting-dropdown-element-using-javascript-or-jquery/ –  May 25 '16 at 19:11
39

If you are using jQuery:

$('#sel').val('bike');
Trevor
  • 6,601
  • 5
  • 34
  • 67
12

try out this....

JSFIDDEL DEMO

using javascript

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

using jQuery

$('#sel').val('car');
Vijay
  • 7,651
  • 9
  • 41
  • 69
1
document.getElementById('drpSelectSourceLibrary').value = 'Seven';
Makyen
  • 29,855
  • 12
  • 76
  • 115