Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

html select element with default not in the options [duplicate]

Tags:

html

Possible Duplicate:
<select> placeholder

I want to do something like this:

<select>
    <option selected="selected">Choose option</option>
    <option>Option 1</option>
    <option>Option 2</option>
    <option>Option 3</option>
    <option>Option 4</option>
</select>

here's the jsfiddle.

now I want the first option the selected one with the content "Choose option" to not be visible in the dropdown. how can i do that, if that's possible with a select element or should i do a custom thing. Thanks in advance.

like image 758
Yahya KACEM Avatar asked Jan 12 '13 23:01

Yahya KACEM


People also ask

How do I set the default selection in HTML?

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 I preselect a select option?

A select box also called drop down box provides an option to list down various options in the form of drop down list. You can also preselect a value in dropdown list of items in HTML forms. For that, add selected in the <option> tag for the value you want to preselect.

How to select element in HTML?

Definition and Usage. The <select> element is used to create a drop-down list. The <select> element is most often used in a form, to collect user input. The name attribute is needed to reference the form data after the form is submitted (if you omit the name attribute, no data from the drop-down list will be submitted) ...

How many types of selects are there in HTML?

There are eight tag-specific attributes commonly used with HTML select tags.


2 Answers

I believe the closest you can get with a plain HTML-solution is to disable that option:

<select>
    <option selected="selected" disabled="disabled">Choose option</option>
    <option>Option 1</option>
    <option>Option 2</option>
    <option>Option 3</option>
    <option>Option 4</option>
</select>

Demo

The element will still appear in the the list, but it will be grayed out and it will not be possible to select it from the dropdown after opening it.

like image 147
Christofer Eliasson Avatar answered Nov 15 '22 20:11

Christofer Eliasson


You could remove the selected element as soon as you open the list:

$('select').click(function () {
  $('option[selected="selected"]', this).remove();
});

I am not aware of any native HTML/HTML5 solution.

like image 44
philipproplesch Avatar answered Nov 15 '22 22:11

philipproplesch