Reputation: 827
I have a select
element of the form:
<select id="test" name="test">
<option value="blah">Test1</option>
<option value="blah">Test2</option>
.
<option value="blah">Testn</option>
</select>
I want to display the text "Select a test" as default. I know the way of doing this is to set a new option
<option selected="selected">Select a test</option>
at the top. But I'm looking for some other way where I don't have to use the tag. Is it possible through javascript (jQuery will also do)?
Upvotes: 0
Views: 1721
Reputation: 26143
I've done this with a dummy entry in the past...
HTML
<select id="test" name="test">
<option value="0">Select an option...</option>
<option value="blah">Test1</option>
<option value="blah">Test2</option>
<option value="blah">Test3</option>
<option value="blah">Test4</option>
<option value="blah">Test5</option>
</select>
Javascript
$("#test").on("change", function() {
if ($(this).val() != "0") {
$("option[value=0]", this).remove();
}
});
Here's a working example on jsFiddle...
The "Select an option" option is removed as soon as you select something else.
Upvotes: 1
Reputation: 122906
Here's a plain js solution:
var selecttest = document.querySelector('#test');
selecttest.insertBefore(new Option('select a test'),selecttest.firstChild);
selecttest.selectedIndex = 0;
Upvotes: 1