Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

default select option as blank

Tags:

html

I have a very weird requirement, wherein I am required to have no option selected by default in drop down menu in HTML. However,

I cannot use this,

<select>    <option></option>    <option>Option 1</option>    <option>Option 2</option>    <option>Option 3</option>  </select>

Because, for this I will have to do validation to handle the first option. Can anyone help me in achieving this target without actually including the first option as part of the select tag?

like image 526
Pankaj Parashar Avatar asked Dec 22 '11 14:12

Pankaj Parashar


People also ask

How do I set the default option in select?

The default value of the select element can be set by using the 'selected' attribute on the required option. This is a boolean attribute. The option that is having the 'selected' attribute will be displayed by default on the dropdown list.

How do you clear the selection in HTML?

To remove the options of an HTML element of select , you can utilize the remove() method: function removeOptions(selectElement) { var i, L = selectElement. options. length - 1; for(i = L; i >= 0; i--) { selectElement.

How do I hide options in select?

You can specify either 'hidden' (without value) or 'hidden="hidden"'. Both are valid. A hidden <option> element is not visible, but it maintains its position on the page. Removing the hidden attribute makes it re-appear.


2 Answers

Maybe this will be helpful

<select>     <option disabled selected value> -- select an option -- </option>     <option>Option 1</option>     <option>Option 2</option>     <option>Option 3</option> </select> 

-- select an option -- Will be displayed by default. But if you choose an option, you will not be able to select it back.

You can also hide it using by adding an empty option

<option style="display:none">

so it won't show up in the list anymore.

Option 2

If you don't want to write CSS and expect the same behaviour of the solution above, just use:

<option hidden disabled selected value> -- select an option -- </option>

like image 123
Gambit Avatar answered Sep 20 '22 21:09

Gambit


You could use Javascript to achieve this. Try the following code:

HTML

<select id="myDropdown">           <option>Option 1</option>          <option>Option 2</option>          <option>Option 3</option>      </select>  

JS

document.getElementById("myDropdown").selectedIndex = -1; 

or JQuery

$("#myDropdown").prop("selectedIndex", -1); 
like image 29
Matschie Avatar answered Sep 17 '22 21:09

Matschie