javascript中的简单年龄验证

时间:2015-11-06 01:10:09

标签: javascript html

我是一个Js noob,我试图制作一个简单的脚本来从两个输入标签中获取值,并根据它们的值更改一个p标签。我可能只是没有使用正确的语法,但我无法在线找到如何执行此操作的答案。

该剧本应该像r级电影的年龄验证。第一个输入是年龄,第二个输入是客户是否有成年人,如果他们是未成年人。

<pre>
<!DOCTYPE html>
<html>
    <input type="text" id="age" value="your age">
    <input type="text" id="adult" value="(y or n)">
    <input type="button" onclick="checkAge()" value="submit">
<p id="answer"></p>
<script>
var age = document.getElementById("age").innerHTML;
var adult = document.getElementById("adult").innerHTML;
var result = document.getElementById("answer").innerHTML;
var oldEnough = false;
function checkAge(){
    if(age.value >= 18){
        oldEnough = true;
    }
    else{
        oldEnough = false;
    }
    if(oldEnough == false){
        if(adult.value == "y"){
            result = "You are not old enough, but have an adult with you.";
        }
        else{
            result = "You are not old enough and are unaccompanied."
        }
    }
    else{
        result = "You are old enough."
    }
}
</script>
</html>
</pre>

2 个答案:

答案 0 :(得分:2)

  1. 不要在输入元素上调用.innerHTML。只需将变量设置为指向元素即可。

  2. 分配结果时,您需要在分配时使用result.innerHTML。将.innerHTML分配给变量只是将元素的当前内容复制为字符串,它不会使result成为对innerHTML属性的引用。

  3. 您应该在parseInt上致电age,因为.value是一个字符串。

  4. function checkAge() {
      var age = document.getElementById("age");
      var adult = document.getElementById("adult");
      var oldEnough = false;
      var result = document.getElementById("answer")
      if (parseInt(age.value, 10) >= 18) {
        oldEnough = true;
      } else {
        oldEnough = false;
      }
      if (oldEnough == false) {
        if (adult.value == "y") {
          result.innerHTML = "You are not old enough, but have an adult with you.";
        } else {
          result.innerHTML = "You are not old enough and are unaccompanied."
        }
      } else {
        result.innerHTML = "You are old enough."
      }
    }
    <input type="text" id="age" placeholder="your age">
    <input type="text" id="adult" placeholder="(y or n)">
    <input type="button" onclick="checkAge()" value="submit">
    <p id="answer"></p>

答案 1 :(得分:0)

如果将输入元素放入表单中,则可以更轻松地访问它们,并且逻辑可以更简单。另外,请确保使用适当的元素和属性,例如不要将值用作一种占位符,它应该是一个合适的默认值(如果有的话)。

并且不要使用占位符代替标签,它们只应用作所需内容类型的提示,不能替换标签。

&#13;
&#13;
=IF(COUNTIFS(A$2:A2,A2,B$2:B2,"<>" & B2)>0,"Error","OK")
&#13;
function checkAge(button) {
  var form = button.form;
  var result = document.getElementById("answer");

  result.innerHTML = form.age.value >= 18? 'You are old enough.' :
                     form.adult.checked? 'You are not old enough, but have an adult with you.' :
                     'You are not old enough and are unaccompanied.';
}
&#13;
&#13;
&#13;