首页 > 解决方案 > 如何在我的 javascript 函数中使用来自 html 表单的输入?

问题描述

我是 js 新手,想在我的 js 'if' 代码中使用输入值。我写了下面的代码,但它没有呈现。你能告诉我我做错了什么吗?

function myFunction() {
  var age = document.getElementById('selection').value;
   if (age < 4) {
    alert('The child is too young');
    } else if (age > 40) {
        alert('You are too old for this course');
    }
}
<form onsubmit=" myFunction()">
    Age: <input type="text" id="selection" name="age">
    <input type="submit" value="submit">
</form>

标签: javascript

解决方案


你很亲密。

这个应该工作

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>js loops</title>
    <link rel="stylesheet" href="loops.css">
    <script>
      function myFunction() {
        var age = document.getElementById('selection').value;
        if (age < 4) {
          alert('The child is too young');
        } else if (age > 40) {
          alert('You are too old for this course');
        }
        return false;
      }
    </script>
  </head>
  <body>
    <form onsubmit="return myFunction()">
      Age: <input type="text" id="selection" name="age">
      <input type="submit" value="submit">
    </form>
  </body>

</html>

推荐阅读