javascript - 如何在我的 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>
解决方案
你很亲密。
这个应该工作
<!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>
推荐阅读
- php - 将 JSON 数组 PHP [] 转换为 {}
- vb.net - 如何从 vb.net 的设备管理器中获取“最后到达日期”属性?
- c++ - 声明 std::pair 时的大小写入无效
- excel-formula - 在excel中提取前10个最大值
- jenkins - 詹金斯找不到 msbuild
- c# - 未注册类型“Microsoft.AspNetCore.Identity.RoleManager`1[Microsoft.AspNetCore.Identity.IdentityRole]”的服务
- loops - Twig 中的 foreach ( $response as $key => $element )
- excel - 使用 VBA 突出显示单元格
- typescript - 注释允许数组或参数传播作为参数的 TypeScript 函数?
- macos - MacOS:如何在有或没有 Chromium 的情况下安装 puppeteer?