JavaScript - a way check if an option of the lt;selectgt; tag is selected(JavaScript - 一种检查 lt;selectgt; 选项的方法标签被选中)
问题描述
我有一个选择标签,我想检查是否选择了飞蛾.
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.
这篇关于JavaScript - 一种检查 <select> 选项的方法标签被选中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:JavaScript - 一种检查 <select> 选项的方法标签被选中
基础教程推荐
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- 直接将值设置为滑块 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01