最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Selectbox hide first option entry on dropdown? - Stack Overflow

programmeradmin3浏览0评论

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

Share Improve this question asked Oct 18, 2011 at 7:58 acctmanacctman 4,34930 gold badges103 silver badges147 bronze badges
Add a comment  | 

5 Answers 5

Reset to default 8

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

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.

发布评论

评论列表(0)

  1. 暂无评论