1. ホーム
  2. javascript

[解決済み] How to hide a <option> in a <select> menu with CSS?

2022-09-04 21:14:50

Question

I've realized that Chrome, it seems, will not allow me to hide <option> in a <select> . Firefox will.

I need to hide the <option> s that match a search criteria. In the Chrome web tools I can see that they are correctly being set to display: none; by my JavaScript, but once then <select> menu is clicked they are shown.

How can I make these <option> s that match my search criteria NOT show when the menu is clicked? Thanks!

How to solved?

You have to implement two methods for hiding. display: none はFFでは機能しますが、ChromeやIEでは機能しません。そこで、2つ目の方法として、ラップして <option><span>display: none . FFではできませんが(仕様上、技術的に無効なHTMLです)、ChromeとIEではでき、オプションは非表示になります。

EDIT: そうそう、これはすでにjQueryで実装しました。

jQuery.fn.toggleOption = function( show ) {
    jQuery( this ).toggle( show );
    if( show ) {
        if( jQuery( this ).parent( 'span.toggleOption' ).length )
            jQuery( this ).unwrap( );
    } else {
        if( jQuery( this ).parent( 'span.toggleOption' ).length == 0 )
            jQuery( this ).wrap( '<span class="toggleOption" style="display: none;" />' );
    }
};

EDIT 2: この関数の使い方はこうです。

jQuery(selector).toggleOption(true); // show option
jQuery(selector).toggleOption(false); // hide option

編集 3: ユーザー1521986の提案による追加チェックを行いました。