Skip to content Skip to sidebar Skip to footer

Selectbox Hide First Option Entry On Dropdown?

Is it possible to hide the first option i.e. when the user clicks the dropdown box to see the options. So the text Select One does not appea

Solution 1:

As 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

Solution 2:

You can use your plain HTML for hiding the first Element of option when select is opened as:

<selectname="list"><optionselected="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/

Solution 3:

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

Solution 4:

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); 
});

Solution 5:

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.

Post a Comment for "Selectbox Hide First Option Entry On Dropdown?"