JavaScript - 一种检查 <select> 选项的方法标签被选中
我有一个选择标签,我想检查是否选择了飞蛾.
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>
这样做:
if (document.registration_form.Birth_Month.value === '')
{
alert('Please fill select Month!');
}
但是这个 JavaScript 对于某些 select-s 有效,而对于其中一些则无效.Obviously, when the "- Month -" is selected the it returnes "- Month -" insted of "" (empty string).我做错了什么?检查标签选择的最佳方法是什么?
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?
推荐答案
浏览器并不总是有一个用于 <select> 的 .value 属性.- 我们以前必须得到<option>的值:
Browsers didn't always have a .value property for <select> - we used to have to get the value of the <option>:
var birthMonth = document.registration_form.Birth_Month;
if (birthMonth.options[birthMonth.selectedIndex].value === '') {
// something
}
我现在使用 jQuery .val().我不记得哪些浏览器缺少 select.value 属性,也许这些浏览器太旧了,我们不需要再担心它们了.但是 jQuery 不使用 select.value - 它遍历每个选项以查找所选选项的值.
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.
当然,如果您知道您将始终将一个空白选项作为第一个选项,只需检查 selectedIndex==0.
Of course, if you know you'll always have a single blank option as the first option, just check for selectedIndex==0.
相关文章