下拉列表中没有空白项的空白 HTML SELECT

如何实现 subj?

当我写道:

<form>
<select>
<option value="0">aaaa</option>
<option value="1">bbbb</option>
</select>
</form>

那么默认选择的项目是“ aaaa”

当我写道:

<form>
<select>
<option value=""></option>
<option value="0">aaaa</option>
<option value="1">bbbb</option>
</select>
</form>

则默认选定项为空白,但此空白项在下拉列表中显示。

如何实现 SELECT 标签与默认的空白值,隐藏在下拉列表?

194844 次浏览

You can't. They simply do not work that way. A drop down menu must have one of its options selected at all times.

You could (although I don't recommend it) watch for a change event and then use JS to delete the first option if it is blank.

You can by setting selectedIndex to -1 using .prop: http://jsfiddle.net/R9auG/.

For older jQuery versions use .attr instead of .prop: http://jsfiddle.net/R9auG/71/.

<select>
<option value="" style="display:none;"></option>
<option value="0">aaaa</option>
<option value="1">bbbb</option>
</select>

Here is a simple way to do it using plain JavaScript. This is the vanilla equivalent of the jQuery script posted by pimvdb. You can test it here.

<script type='text/javascript'>
window.onload = function(){
document.getElementById('id_here').selectedIndex = -1;
}
</script>

.

<select id="id_here">
<option>aaaa</option>
<option>bbbb</option>
</select>

Make sure the "id_here" matches in the form and in the JavaScript.

Just use disabled and/or hidden attributes:

<option selected disabled hidden style='display: none' value=''></option>
  • selected makes this option the default one.
  • disabled makes this option unclickable.
  • style='display: none' makes this option not displayed in older browsers. See: Can I Use documentation for hidden attribute.
  • hidden makes this option to don't be displayed in the drop-down list.

Simply using

<option value="" selected disabled>Please select an option...</option>

will work anywhere without script and allow you to instruct the user at the same time.

You can try this snippet

$("#your-id")[0].selectedIndex = -1

It worked for me.

For purely html @isherwood has a great solution. For jQuery, give your select drop down an ID then select it with jQuery:

<form>
<select id="myDropDown">
<option value="0">aaaa</option>
<option value="1">bbbb</option>
</select>
</form>

Then use this jQuery to clear the drop down on page load:

$(document).ready(function() {
$('#myDropDown').val('');
});

Or put it inside a function by itself:

$('#myDropDown').val('');

accomplishes what you're looking for and it is easy to put this in functions that may get called on your page if you need to blank out the drop down without reloading the page.