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";
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).
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.
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; } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With