javascript条件onclick表单

时间:2015-11-03 16:29:31

标签: javascript html forms

我不能在这个项目中使用JQuery。

我正在尝试从3个单选按钮中收集3个变量。提交此表单将触发一个函数,该函数将使用简单的条件检查三个变量。这将运行第一行或(否则)运行第二行代码。我对条件(它出现)有问题。我总是得到第一线,而不是第二线。



function valid() {
  var q1 = document.getElementById("ques1").value;
  var q2 = document.getElementById("ques2").value;
  var q3 = document.getElementById("ques3").value;
  if (q1 ==="5" && q2 ==="5" && q3 ==="5" ) {
    alert("Thank you for your interest in acme employment. We are not able to consider you for employment at this time. ");
  } else {
    window.location.assign("http://acmeemployment.com");
    //window.location.assign("http://www.w3schools.com");
  }
}

<form action="" method="">

  <p>Are you 18 years of age or older?*<br/>
    <input type="radio" name="q1" id="ques1" value="5">Yes
    <br/>
    <input type="radio" name="q1" value="7">No
  </p>

  <p>Are you willing to take a drug screen according to our policy?*<br/>
    <input type="radio" name="q2" id="ques2" value="5">Yes
    <br/>
    <input type="radio" name="q2" value="7">No
  </p>

  <p>Will you release your background information inclusive of ciminal records?*<br/>
    <input type="radio" name="q3" id="ques3" value="5">Yes
    <br/>
    <input type="radio" name="q3" value="7">No
  </p>

  <input type="button" value="Submit" onclick="valid()" />

</form>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

您的代码未检查所选的单选按钮。您可以使用document.querySelector()查找所选的单选按钮。

此外,您的逻辑似乎是倒退的,并且您想要检查!== "5"

function valid() {
  var q1 = document.querySelector("[name='q1']:checked").value;
  var q2 = document.querySelector("[name='q2']:checked").value;
  var q3 = document.querySelector("[name='q3']:checked").value;
  if (q1 ==="5" && q2 ==="5" && q3 ==="5" ) {
    console.log("Thank you for your interest in acme employment. We are not able to consider you for employment at this time. ");
  } else {
    console.log("redirect to http://acmeemployment.com");
  }
}
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
<form action="" method="">

  <p>Are you 18 years of age or older?*<br/>
    <input type="radio" name="q1" id="ques1" value="5">Yes
    <br/>
    <input type="radio" name="q1" value="7">No
  </p>

  <p>Are you willing to take a drug screen according to our policy?*<br/>
    <input type="radio" name="q2" id="ques2" value="5">Yes
    <br/>
    <input type="radio" name="q2" value="7">No
  </p>

  <p>Will you release your background information inclusive of ciminal records?*<br/>
    <input type="radio" name="q3" id="ques3" value="5">Yes
    <br/>
    <input type="radio" name="q3" value="7">No
  </p>

  <input type="button" value="Submit" onclick="valid()" />

</form>