如何使用javascript验证两个下拉框焦点

时间:2015-06-29 10:55:19

标签: javascript jquery html

我想验证两个下拉框。如果未选择下拉列表,则会提醒用户从下拉列表中选择值。它应该集中相应的下拉列表。 这是我的代码,其中一些

<html> 
<head> 
<title>sample</title>
</head>
<script type="text/javascript" language="javascript"> 

function validator(theSelect)
{


  var bcolor = document.forms["register"]["bcolor"].value;
 if (bcolor == "") {
     alert("Please Select Your color1");
     return false;      
 }
  var bcolor1 = document.forms["register"]["bcolor1"].value;
 if (bcolor1 == "") {
     alert("Please Select Your color2");
     return false;       
 }
 if (theSelect[theSelect.selectedIndex].defaultSelected)
return true;
}
</script>  
<body>
<form method="post" action="sample.php" onSubmit="return validator(this)" name="register">
<select name="bcolor" size="1">
<option value="" selected="selected">Pick a Color</option>
<option value="rd">Red</option>
<option value="yl">Yellow</option>
<option value="gr">Green</option>
</select>

<select name="bcolor1" size="1">
<option value="" selected="selected">Pick a Color</option>
<option value="rd">Red</option>
<option value="yl">Yellow</option>
<option value="gr">Green</option>
</select>
<input type="submit">
</form>
</body> 
</html> 

3 个答案:

答案 0 :(得分:0)

只需使用focus()

if (bcolor == "") {
     alert("Please Select Your color1");
     document.forms["register"]["bcolor"].focus();//
     return false;      
 }
  var bcolor1 = document.forms["register"]["bcolor1"].value;
 if (bcolor1 == "") {
     alert("Please Select Your color2");
     document.forms["register"]["bcolor1"].focus();//
     return false;       
 }

答案 1 :(得分:0)

这是一个工作JSfiddle

function validator(theSelect)
{
    var bcolor = document.forms["register"]["bcolor"];
    if (bcolor.value == "") {
        alert("Please Select Your color1");
        bcolor.focus();
        return false;      
    }
    var bcolor1 = document.forms["register"]["bcolor1"];
     if (bcolor1.value == "") {
         alert("Please Select Your color2");
         bcolor1.focus();
         return false;       
     }
     if (theSelect[theSelect.selectedIndex].defaultSelected)
        return true;
}

答案 2 :(得分:0)

只需 在目标元素上调用focus()方法

你的第一次警报后      //代码聚焦第一个下拉列表(bcolor)
 的 document.forms [ “注册”] [ “bcolor”]聚焦();

第二次警报后      //代码聚焦第二个下拉列表(bcolor1)
 的 document.forms [ “注册”] [ “bcolor1”]聚焦();