Is it possible to hide the first option i.e. <option>Select One</option>
when the user clicks the dropdown box to see the options. So the text Select One does not appear in the list
Is it possible to hide the first option i.e. <option>Select One</option>
when the user clicks the dropdown box to see the options. So the text Select One does not appear in the list
5 Answers
Reset to default 8As there is no reliable cross browser way to hide option
elements, your best bet is to remove it on focus
and add it again on blur
:
jQuery(document).ready(function () {
var first = jQuery('#myselect').find('option').first();
jQuery('#myselect').on('focus', function (e) {
first.remove();
}).on('blur', function (e) {
jQuery(this).find('option').first().before(first);
});
});
Here's a working example
You can use your plain HTML for hiding the first Element of option when select is opened as:
<select name="list">
<option selected="selected" hidden>First Element</option>
<option>Second Element</option>
<option>Third Element</option>
</select>
Here is the working fiddle: https://jsfiddle.net/sujan_mhrzn/y5kxtkc6/
As a quick CSS option you could give the dropdown an id and then
#cat option:first-child {
display: none;
}
The above uses #cat as the id for the dropdown
Tutorial for this solution
The only cross-browser method is to remove it entirely. In plain ol' JS:
var sel = document.getElementById("mySelect");
sel.onfocus = function () {
select.onfocus = null;
sel.removeChild(sel.firstChild);
}
jQuery:
$("#mySelect").focus(function () {
$(this).remove(this.firstChild).unbind(arguments.callee);
});
If you want to remove the option, the simples code would be:
var mySelect = document.getElementById('mySelect');
mySelect.onfocus = function() { mySelect.removeChild(mySelect.options[0]); }
where mySelect
is the id of the select box.
Edit: I changed the code to append an event listener for the focus event. This code, however, will remove the first option every time you select the select box. Pretty sure this is not what you need. You could use onblur to append the option again, but I don't know if that's what you need. Please clarify what you want to do.