【问题标题】:How to display username input after verification using JavaScript and HTML如何在使用 JavaScript 和 HTML 验证后显示用户名输入
【发布时间】:2020-04-09 09:32:00
【问题描述】:

所以我正在为一家需要年龄验证的啤酒厂开发一个网站。验证有效,它会询问您的出生日期和名字。我唯一需要做的就是在网站上显示名字并打上一句问候“嘿,“你的名字”!欢迎来到我们的啤酒厂!只有你年龄在 18 到 101 岁之间。

//get birthdate
function calculateAge(dateString) {
  var today = new Date();
  var birthDate = new Date(dateString);
  var age = today.getFullYear() - birthDate.getFullYear();
  var m = today.getMonth() - birthDate.getMonth();
  if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
    age--;
  }
  return age;
}

//validate user age
const displayCheck = window.prompt(
  "Please Enter your birthdate in format YYYY/MM/DD"
);
const name = window.prompt("Please Enter your Name");
const age = calculateAge(displayCheck);
if (age < 18) {
  window.alert(
    "You Submitted that you are " + age + "years old, " + "" + name + "."
  );
  window.alert(
    "You must be at least eighteen years old to visit this site. You will be re-directed to an 
    appropriate site shortly!"
  );
  window.location = "http://disney.com";
} else if (age > 18 && age < 101) {
  window.alert(
    "You are old enough to visit the site," + " " + "Welcome " + "" + name + "!"
  );
  document.write(name)
} else {
  window.alert("You must be honest about your age, " + name + ".");
}
<h1 class="display-2">
  Hey
  <script src="script.js">
    document.write(name)
  </script>!
</h1>

好消息是它有效,但代码验证器不喜欢它。

还有什么其他方法可以做到这一点?

谢谢

【问题讨论】:

标签: javascript html css verification


【解决方案1】:

您可以在 html 中使用事件 onchange 调用函数,并使用 javascript 中的值来显示输出。要在我的 sn-p 中对其进行测试,请在输入中写下您的姓名,并在完成后单击其外部。这就是触发事件的时间。

function myFunction() {
  var name = document.getElementById("firstName").value;
  document.getElementById("greeting").innerHTML = "Hello " + name + " !";
}
<input id="firstName" type="text" onchange="myFunction()"><br>
<div id="greeting"></div>

如果您想添加一个条件以仅在用户超过 18 岁时显示姓名,您需要将事件放入年龄输入中,并根据其值,您可以显示他的姓名或消息.. 或者什么都没有。这取决于你!

function myFunction() {
  var age = document.getElementById("age").value;

  if (age > 17) {
    var name = document.getElementById("firstName").value;
    document.getElementById("greeting").innerHTML = "Hello " + name + " !";
  } else {
    document.getElementById("greeting").innerHTML = "Sorry, you are not over 18 years old.";
  }
}
<input id="firstName" type="text" placeholder="enter your name">
<input id="age" type="text" onchange="myFunction()" placeholder="how old are you?"><br>
<div id="greeting"></div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    • 2019-04-26
    • 2019-11-29
    • 2015-08-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多