Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
369 views
in Technique[技术] by (71.8m points)

jquery - How can I hide select options with JavaScript? (Cross browser)

This should work:

$('option').hide(); // hide options

It works in Firefox, but not Chrome (and probably not in IE, not tested).

A more interesting example:

<select>
    <option class="hide">Hide me</option>
    <option>visible option</option>
</select>
<script type="text/javascript">
// try to hide the first option
$('option.hide').hide();

// to select the first visible option
$('option:visible').first().attr('selected', 'selected');
</script>

Or see the example at http://jsfiddle.net/TGxUf/

Is the only option to detach the option elements from the DOM? I need to show them again later, so this would not be very effective.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Unfortunately, you can't hide option elements in all browsers.

In the past when I have needed to do this, I have set their disabled attribute, like so...

$('option').prop('disabled', true);

I've then used the hiding where it is supported in browsers using this piece of CSS...

select option[disabled] {
    display: none;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...