Reputation: 4824
Imagine a select HTML element below:
<select id="mySelect">
<option>Apple</option>
<option>Orange</option>
<option>Pineapple</option>
<option>Banana</option>
</select>
I want that when this DOM element is rendered, the selected value should be blank and not either of 4 fruits.
I do not want to include blank as another option.
Is it possible?
That is I do not want to add another item like:
<select id="mySelect">
<option>Select an item </option>
<option>Apple</option>
<option>Orange</option>
<option>Pineapple</option>
<option>Banana</option>
</select>
OR
<select id="mySelect">
<option></option>
<option>Apple</option>
<option>Orange</option>
<option>Pineapple</option>
<option>Banana</option>
</select>
Upvotes: 4
Views: 8853
Reputation: 2509
This will work fine for you
Use this HTML
<select id="mySelect">
<option>Apple</option>
<option>Orange</option>
<option>Pineapple</option>
<option>Banana</option>
</select>
And in jQuery use
$('#mySelect').prop('selectedIndex', -1);
Javascript version (tested on lastest chrome, firefox & IE 11)
document.getElementById("mySelect").selectedIndex = -1
this should make the drop down list display blank without adding an extra blank option to the list
Upvotes: 6
Reputation: 1046
<option selected disabled value=''></option>
selected
makes this option the default one.
disabled
makes this option unclickable.
Upvotes: 2
Reputation: 31
I just found a very pretty solution:
<pre>
<label for="hardness">Select the hardness</label> :
<select name="hardness" id="hardness">
<option selected="selected" disabled="disabled"></option>
<option value="3">Easy</option>
<option value="6">Medium</option>
<option value="10">Hard</option>
</select>
</pre>
Now selectHardness.selectedIndex always > 0;
Upvotes: 3
Reputation:
You can't do this with plain HTML. Check the MDN and official W3C HTML5.x nightly build:
You really need to switch it out with JavaScript and using the selected attribute on a "fake" option.
These are the availabilities of attributes (properties) of the <select>
element:
Global
accesskey class contenteditable contextmenu dir draggable dropzone hidden id inert spellcheck style tabindex title translate
Select
autofocus disabled form multiple name required size
As the OP seemed to allow JavaScript as an alternative, but not jQuery I've added a plain JavaScript example to prepend a empty (selected) option tag;
var fakeOpt = document.createElement('option');
var myList = document.getElementById('mySelect');
fakeOpt.selected = 'selected';
myList.insertBefore(fakeOpt, myList[0]);
// Listen to a change
myList.onchange = function(evt){
var clicked_option = myList.options[myList.selectedIndex].text;
if (clicked_option.trim() != '') {
console.log(clicked_option);
}
else {
console.log('Empty option selected');
}
};
With this there is no need to fill in one by hand in the HTML code.
Here's a JSfiddle; http://jsfiddle.net/VjCbE/3/
Upvotes: 4