How To Set Default Value For Html Select?
I have a HTML select like this: and I hav
Solution 1:
You first need to add values to your select
options and for easy targetting give the select
itself an id
.
Let's make option b
the default:
<selectid="mySelect"><option>a</option><optionselected="selected">b</option><option>c</option></select>
Now you can change the default selected value with JavaScript like this:
<script>var temp = "a";
var mySelect = document.getElementById('mySelect');
for(var i, j = 0; i = mySelect.options[j]; j++) {
if(i.value == temp) {
mySelect.selectedIndex = j;
break;
}
}
</script>
Also we can use "text" property of i to validate:
if(i.text == temp)
See it in action on codepen.
Solution 2:
Note: this is JQuery. See Sébastien answer for Javascript
$(function() {
var temp="a";
$("#MySelect").val(temp);
});
<selectname="MySelect"id="MySelect"><optionvalue="a">a</option><optionvalue="b">b</option><optionvalue="c">c</option></select>
Solution 3:
You should define the attributes of option
like selected="selected"
<select><optionselected="selected">a</option><option>b</option><option>c</option></select>
Solution 4:
Simplay you can place HTML select attribute to option
a
like shown below
Define the attributes like selected="selected"
<select><optionselected="selected">a</option><option>b</option><option>c</option></select>
Solution 5:
you can define attribute selected="selected" in Ex a
Post a Comment for "How To Set Default Value For Html Select?"