Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select a value in a select dropdown with JavaScript?

Tags:

javascript

i have a drop down like this

<select style="width: 280px" id="Mobility" name="Mobility">   <option selected="">Please Select</option>   <option>K</option>   <option>1</option>   <option>2</option>   <option>3</option>   <option>4</option>   <option>5</option>   <option>6</option>   <option>7</option>   <option>8</option>   <option>9</option>   <option>10</option>   <option>11</option>   <option>12</option> </select> 

I use this line to select a value it works in Mozilla not in IE? Why its not working?

var element = document.getElementById("Mobility"); element.value = "10"; 
like image 840
karthick Avatar asked Nov 15 '11 17:11

karthick


People also ask

How do you select a value in JavaScript?

To get the value of a select or dropdown in HTML using pure JavaScript, first we get the select tag, in this case by id, and then we get the selected value through the selectedIndex property. The value "en" will be printed on the console (Ctrl + Shift + J to open the console).

How do I select a value from a dropdown in HTML?

The select tag in HTML is used to create a dropdown list of options that can be selected. The option tag contains the value that would be used when selected. The default value of the select element can be set by using the 'selected' attribute on the required option. This is a boolean attribute.


1 Answers

Use the selectedIndex property:

document.getElementById("Mobility").selectedIndex = 12; //Option 10 

Alternate method:

Loop through each value:

//Get select object var objSelect = document.getElementById("Mobility");  //Set selected setSelectedValue(objSelect, "10");  function setSelectedValue(selectObj, valueToSet) {     for (var i = 0; i < selectObj.options.length; i++) {         if (selectObj.options[i].text== valueToSet) {             selectObj.options[i].selected = true;             return;         }     } } 
like image 89
James Hill Avatar answered Oct 12 '22 10:10

James Hill