Javascript 检查HTML下拉选项
我有一个HTML下拉控件。我想检查,如果其中的文本是“选择”,它必须显示错误消息。我正在使用下面的代码来实现这一点,但它不起作用Javascript 检查HTML下拉选项,javascript,html,Javascript,Html,我有一个HTML下拉控件。我想检查,如果其中的文本是“选择”,它必须显示错误消息。我正在使用下面的代码来实现这一点,但它不起作用 if (document.getElementById("StudentCountry").value == "Select") { alert("Please select your country."); document.getElementById("StudentCountry").focus();
if (document.getElementById("StudentCountry").value == "Select")
{
alert("Please select your country.");
document.getElementById("StudentCountry").focus();
return false;
}
或
检查所选值=“选择”
或
检查selected value=“select”此javascript代码如何嵌入到html文件中?它只是在一个脚本元素中,而不是在一个独立的函数中吗?如果是这样,函数可能总是返回null,因为下拉列表在使用时没有加载。否则代码应该可以工作。只需输入一个函数,比如checkCountry(),并将其作为onchange=“checkCountry();”添加到标记中。 第二件可能破坏代码的事情是检查“选择”文本。如果检查某个选项的值,它很可能会检查值属性,例如: 挑选 在本例中,select是用小写字母编写的,与您的==不符
我希望这能有所帮助。这个javascript代码是如何嵌入到您的html文件中的?它只是在一个脚本元素中,而不是在一个独立的函数中吗?如果是这样,函数可能总是返回null,因为下拉列表在使用时没有加载。否则代码应该可以工作。只需输入一个函数,比如checkCountry(),并将其作为onchange=“checkCountry();”添加到标记中。
var box = document.getElementById("StudentCountry");
if(box.options[box.selectedIndex].text == "Select")
第二件可能破坏代码的事情是检查“选择”文本。如果检查某个选项的值,它很可能会检查值属性,例如:
挑选
在本例中,select是用小写字母编写的,与您的==不符
我希望这会有所帮助。您的代码似乎很完美。请检查默认选项值是否为“选择”
var box = document.getElementById("StudentCountry");
if(box.options[box.selectedIndex].text == "Select")
函数验证(){
警报('ddd='+document.getElementById(“StudentCountry”).value);
if(document.getElementById(“StudentCountry”).value==“select”)
{
警告(“请选择您的国家/地区”);
document.getElementById(“StudentCountry”).focus();
返回false;
}
返回false;
}
---------请选择---------
印度
无人机
英国
您的代码似乎很完美。请检查默认选项值是否为“选择”
函数验证(){
警报('ddd='+document.getElementById(“StudentCountry”).value);
if(document.getElementById(“StudentCountry”).value==“select”)
{
警告(“请选择您的国家/地区”);
document.getElementById(“StudentCountry”).focus();
返回false;
}
返回false;
}
---------请选择---------
印度
无人机
英国
请发布HTML/PHP/任何代码好吗?请发布HTML/PHP/任何代码好吗?它位于不同的函数中。它位于不同的函数中。这可能不是“最佳”解决方案,但代码可以复制/粘贴并随时使用。这可能不是“最佳”解决方案,但代码可以复制/粘贴并随时使用。
var box = document.getElementById("StudentCountry");
if(box.options[box.selectedIndex].text == "Select")
<html>
<head>
<script language="javascript">
function validate(){
alert('ddddddddddd ='+document.getElementById("StudentCountry").value);
if (document.getElementById("StudentCountry").value == "select")
{
alert("Please select your country.");
document.getElementById("StudentCountry").focus();
return false;
}
return false;
}
</script>
</head>
<body>
<select id="StudentCountry">
<option value="select" >---------Please Select ---------</option>
<option value="India" >India</option>
<option value="USA" >UAS</option>
<option value="UK" >UK </option>
</select>
<a onclick="javascript:validate();" href="#">click here to validate</a>