views:

41

answers:

2

I want to select a value in a select/option dropdown using javascript only.

Revised sorry for confusion. Here is revised code.

document.getElementById("sel_activity").value = activity;

This will also work, but is a bit longer..

<select id='sel_activity'>
<option value='CYC'>Cycle Count</option>
<option value='INV'>Inventory Count</option>
<option value='INVDROP'>Inventory Drop off</option>
<option value='INVPICK'>Inventory Pick up</option>
<option value='TRAIN'>Training</option>
</select>

<script type="text/javascript">

var select = 'CYC';
var myselect=document.getElementById("sel_activity")
for (var i=0; i<myselect.options.length; i++){
 if (myselect.options[i].value == select)
 {
    myselect.options[i].selected = true;
 }
 else
 {
    myselect.options[i].selected = false;
 } 
} 
</script>
A: 
var myselect=document.getElementById("sel_activity")
myselect.options[myselect.options.length]=new Option("text","value");

http://devedge-temp.mozilla.org/library/manuals/2000/javascript/1.3/reference/option.html

mplungjan
Sorry I did not mean add a new option, but change the displayed option.
robert
A: 

using jQuery

$("#sel_activity").val("CYC")

jQuery is a lightweight javasscript library which is very helpful in DOm traveral,event handling and ajax intearactions.

http://jquery.com/

Adding jQuery to your page is simple as adding one line of code in the head section to include the jQuery library

<head>
  <script type="text/javascript" src="h ttp://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
Shyju
My clients include blackberry devices which don't work well with most JS libarries.
robert
the jQuery library is made of only javascript.You said you need to do this in javascript.
Shyju
true indeed, but much more javascript than I want to be loading a mobile device. Also BB before OS5.o have unresolved compatibility issues with jquery. Hopefully the jQuery Mobile project will address these.http://jquerymobile.com/
robert
@robert: thanks for the link .jQuery rocks
Shyju