具有多个验证的表单中的单选按钮的Javascript验证

时间:2014-05-18 00:57:05

标签: javascript forms validation radio-button

我无法找到验证性别选择操作按钮的方法。我已经努力做到这一点,说按钮不能保留为空,但它仍然认为一个按钮为空,并且不让我继续。我尝试了不同的变化,比如说男性和女性都没有被选中然后返回假,但它仍然不能为我工作。我开始认为我所采用的方法可能不正确。您要查看下面的主要问题是两个单选按钮,但我已将其余代码作为Javascript的上下文包含在内。其余的代码工作正常,只有单选按钮比我挣扎。感谢。

HTML

<form action="ReviewPHP.php" name="review" onsubmit="return validateForm()"> 

  <fieldset> 
    Title: <input type="text" name="Title">
    </br>
    Email Address: <input type="text" name="Email">
    <br/> 
    Rating: <select name="Rating"> 
      <option value="0"></option> 
      <option value="1">Excellent</option> 
      <option value="2">Good</option> 
      <option value="3">Bad</option> 
      <option value="4">Awful</option> 
    </select>
    <br/> 
    <textarea name ="Comments" rows="8" colspan="40">Comments: 
    </textarea> 
    <br/>

    <input type="radio" name="Gender" id="male" value="male">Male
    <input type="radio" name="Gender" id="female" value="female">Female

  </fieldset> 

  <fieldset> 
    <input class="button" type="submit" value="Submit"/> 
  </fieldset> 

</form>

的Javascript

function validateForm()
{ //Variable declarations for form inputs 

  var t = document.forms["review"]["Title"].value;
  var e = document.forms["review"]["Email"].value;
  var r = document.forms["review"]["Rating"].value;
  var c = document.forms["review"]["Comments"].value;
  var b = document.forms["review"]["Gender"].value;
  var atsymb = e.indexOf("@");
  var dotsymb = e.lastIndexOf(".");

  if (t == null || t == "") {
    document.getElementById("valAlert").innerHTML = "Title Missing";
    return false;
  }

  else if (e == null || e == "" || atsymb < 1 || dotsymb < atsymb + 2 || dotsymb + 2 >= e.length)
  {
    document.getElementById("valAlert").innerHTML = "Email Missing";
    return false;
  }

  else if (r == "0") {
    document.getElementById("valAlert").innerHTML = "Please Rate the Movie, it's why you're here";
    return false;
  }

  else if (c == null || c == "" || c.length < 10) {
    document.getElementById("valAlert").innerHTML = "Reviews gotta be at least 10 characters!";
    return false;
  }

  else if (b == null) {
    document.getElementById("valAlert").innerHTML = "Please select Gender";
    return false;
  }

  else {
    alert("Review for " + t + " has been submitted, Good Job!");
    return true;
  }
} 

2 个答案:

答案 0 :(得分:1)

您可以使用checked属性来了解是否选中了某个选项。

    document.getElementById('male').checked

该文件在这里: http://www.w3schools.com/jsref/prop_radio_checked.asp

我想你想做的是这样的事情:

var b = "";
if (document.getElementById('male').checked) {

  b = document.getElementById('male').value;

}else if(document.getElementById('female').checked) {

  b = document.getElementById('female').value;

}

if(b == "" | b == null ){
  // alert    
}

希望这有帮助。

答案 1 :(得分:0)

您必须检查b是否未定义。

if (!b || b == null) {

我减少了javascript并做了一个简单的工作演示:

http://jsfiddle.net/z7e7D/