-1

我正在尝试验证 javascript 中的单选按钮和选项框。这是代码,但它不起作用... OprionBox 和 Radio 的 Javascript 代码:

function checkCountry()
        {
        if(document.form.country.selectedIndex=="")
        {
        alert("Please select country from the list");
        return false;  
        }
        return true
        }
function checkGender()
        {
        if(!document.getElementsByName("sex")[0].checked && !document.getElementsByName("sex")[1].checked)
        {
        alert("Select Male/Female");
        return false;
        }
        return true;
        }
function validate()
      {
            checkCountry();
            checkGender();
      }

HTML 代码:

<form name="form" method="post" onSubmit="return validate()">                
    <select name="country">
    <option value="select">(Please select a country)</option>
    <option value="pk">Pakistan</option>
    <option value="chn">China</option>
    <option value="uk">United Kingdom</option>
    <option value="usa">United States of America</option>
    <option value="ir">Iran</option>
    <option value="ma">Malaysia</option>
    </select><br>
    <input type="radio" name="sex" value="male">Male<br>
    <input type="radio" name="sex" value="female">Female<br></form>

请帮忙...

4

3 回答 3

0

这是整个代码,它工作正常

<html>
<head>
<script type="text/javascript">
function checkGender()
        {
        if(!document.getElementsByName("sex")[0].checked && !document.getElementsByName("sex")[1].checked)
        {
        alert("Select Male/Female");
        return false;
        }
        return true;
        }
function checkCountry()
        {

      if(document.getElementsByName("country")[0].selectedIndex==0)
        {
        alert("Please select country from the list");
        return false;  
        }
        return true
        }
function validate()
      {
            checkCountry();
           checkGender();
      }
</script>
</head>
<body>

<form onSubmit="return validate()" >
  <select name="country">
    <option value="select">(Please select a country)</option>
    <option value="pk">Pakistan</option>
    <option value="chn">China</option>
    <option value="uk">United Kingdom</option>
    <option value="usa">United States of America</option>
    <option value="ir">Iran</option>
    <option value="ma">Malaysia</option>
    </select><br>
    <input type="radio" name="sex" value="male">Male<br>
    <input type="radio" name="sex" value="female">Female<br>
  <input type="submit" value="Submit" >
</form>

</body>
</html>
于 2013-01-07T10:30:33.297 回答
0

您必须将检查所选索引的行更改为:

if(document.form.country.selectedIndex === 0)那是因为您的“请选择一个国家”条目,您将始终拥有一个选定的索引。

如果我然后<input type="submit" value="test"/>在您的表单中添加以测试提交,我将收到您的错误消息。

请参阅http://jsbin.com/oviped/2/edit它正在工作!

于 2013-01-07T09:31:31.530 回答
0

更改if(document.form.country.selectedIndex=="")if(document.getElementsByName("country").selectedIndex=="0")

于 2013-01-07T09:56:38.323 回答