Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML select box with blank to be displayed until you select any of them

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>
like image 343
Cute_Ninja Avatar asked Dec 09 '22 16:12

Cute_Ninja


1 Answers

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

like image 188
Praveen Dabral Avatar answered Dec 11 '22 07:12

Praveen Dabral