javascript 在 html 选择元素中显示空值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10703947/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
show empty value in html select element
提问by Koen Peters
I have an HTML select element (combo box) in a form with a couple if options in it. As always each option has a specific value. During the page's initialization I get a value from the server that I must use as the selected option in the list. Sometimes however I get a value from the server that does not match any of the available options. (grrrr)
我有一个表单中的 HTML 选择元素(组合框),其中包含几个 if 选项。与往常一样,每个选项都有特定的值。在页面初始化期间,我从服务器获取一个值,我必须将其用作列表中的选定选项。然而,有时我从服务器获得一个与任何可用选项都不匹配的值。(咕噜噜)
I want to let the user know that the value I got from the server is not a valid option. What I'd like to do is show an empty select box (as if no selection was made) without having an actual empty option as one of the options. Also I'd like to use the default select element if possible. Is something like this possible?
我想让用户知道我从服务器获得的值不是一个有效的选项。我想要做的是显示一个空的选择框(就像没有选择一样)而没有实际的空选项作为选项之一。如果可能的话,我也想使用默认的选择元素。这样的事情可能吗?
Edit: When you set the value for a combox to '' in IE9 (I used $('select').val('') ) it empties the text in the combo box which is exactly what I need. Unfortunately only IE9 does this, so this is not an option.
编辑:当您在 IE9 中将组合框的值设置为 '' (我使用了 $('select').val('') )时,它会清空组合框中的文本,这正是我所需要的。不幸的是,只有 IE9 会这样做,所以这不是一个选项。
采纳答案by naivists
Out of the box, HTML selects do not provide such functionality. You will have to add an empty <option value="somethingwrong">Please, pick a value</option>
element and use scripting to check if the user has selected this specific value. I'd suggest catching both onchange
event of the dropdown and onsubmit
event of whole form.
开箱即用的 HTML 选择不提供此类功能。您必须添加一个空<option value="somethingwrong">Please, pick a value</option>
元素并使用脚本来检查用户是否选择了此特定值。我建议同时捕获onchange
下拉onsubmit
事件和整个表单的事件。