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?
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.
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.
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.
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>
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With