JavaScript - 检查< select>的选项的方法标签被选中 [英] JavaScript - a way check if an option of the <select> tag is selected

查看:93
本文介绍了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用于某些选择工作,对于其中一些工作,不。显然,当选择 - 月 - 时,它会返回 - 月 - ,(空字符串)。我做错了什么?检查标签选择的最佳方法是什么?

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属性 - 我们以前必须得到<选项>的值:

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===''){



<我现在使用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 - 检查&lt; select&gt;的选项的方法标签被选中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆