JavaScript - 一种检查
我有一个选择标签,我想检查是否选择了飞蛾。
<select name="Birth_Month">
<option value="" SELECTED>- Month -</option>
<option value="January">January</option>
<option value="Fabruary">Fabruary</option>
<option value="March">March</option>
<option value="April">April</option>
<option value="May">May</option>
<option value="June">June</option>
<option value="July">July</option>
<option value="August">August</option>
<option value="September">September</option>
<option value="October">October</option>
<option value="November">November</option>
<option value="December">December</option>
</select>
所以这样做:
if (document.registration_form.Birth_Month.value === '')
{
alert('Please fill select Month!');
}
但是这个 JavaScript 对于某些 select-s 有效,而对于其中一些则无效。显然,当选择“- Month -”时,它返回“- Month -”而不是“”(空字符串)。我做错了什么?检查标签选择的最佳方法是什么?
I have a select tag and I want to check if a moth is selected.
<select name="Birth_Month">
<option value="" SELECTED>- Month -</option>
<option value="January">January</option>
<option value="Fabruary">Fabruary</option>
<option value="March">March</option>
<option value="April">April</option>
<option value="May">May</option>
<option value="June">June</option>
<option value="July">July</option>
<option value="August">August</option>
<option value="September">September</option>
<option value="October">October</option>
<option value="November">November</option>
<option value="December">December</option>
</select>
So do this:
if (document.registration_form.Birth_Month.value === '')
{
alert('Please fill select Month!');
}
But this JavaScript for some select-s work and for some of them, does not. Obviously, when the "- Month -" is selected the it returnes "- Month -" insted of "" (empty string). What I have done wrong? What is the best way of checking the tag's selection?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
浏览器并不总是有
我现在使用 jQuery .val()。我不记得哪些浏览器缺少 select.value 属性,也许这些浏览器太旧了,我们不需要再担心它们了。但 jQuery 不使用 select.value - 它循环遍历每个选项来查找所选选项的值。
当然,如果您知道第一个选项始终是一个空白选项,则只需检查 selectedIndex==0 即可。
Browsers didn't always have a .value property for <select> - we used to have to get the value of the <option>:
I use jQuery .val() now. I don't remember which browsers lack the select.value property, and maybe those browsers are so old that we don't need to worry about them anymore. But jQuery doesn't use select.value - it loops through each of the options to find the selected option's value.
Of course, if you know you'll always have a single blank option as the first option, just check for selectedIndex==0.
我相信整数是选项值的更好实践。无论如何,下面的代码片段并不关心您的默认选项值是空字符串还是零值。
I believe integers are a better practice for option values. Anyhow, the snippet below doesn't care if your default option value is an empty string or a zero value.
您不需要使用“selectedIndex”
或
You do not need to use 'selectedIndex'
OR