i have a drop down like this
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;
}
}
}
Using some ES6:
Get the options first, filter the value based on the option and set the selected attribute to true.
window.onload = () => {
Array.from(document.querySelector(`#Mobility`).options)
.filter(x => x.value === "12")[0]
.setAttribute('selected', true);
};
<select style="width: 280px" id="Mobility" name="Mobility">
<option selected disabled>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>
This may do it
document.forms['someform'].elements['someelement'].value
Yes. As mentioned in the posts, value
property is nonstandard and does not work with IE. You will need to use the selectedIndex
property to achieve this. You can refer to the w3schools DOM reference to see the properties of HTML elements. The following link will give you the list of properties you can work with on the select element.
http://www.w3schools.com/jsref/dom_obj_select.asp
Update
This was not supported during 2011 on IE. As commented by finnTheHuman, it is supported at present.