javascript - 提交表单时未显示警报消息
问题描述
我刚开始学习 HTML/JavaScript。我有一个表单,提交时它应该向用户显示输入数据,我尝试了警报和 .html() 方法,但似乎都没有显示信息。
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script src="scripts/jquery-3.2.1.js"></script>
<script>
function displayInfo() {
let product = ($('#productName').val());
let quantity = parseInt($('#qty').val());
if ($('#delivery:checked').val() == 'y'){
let delivery = "Delivery required";
}
else{
let delivery = "Delivery not required";
}
var info = "Product name: " + product + "<br>" + "Quantity: " + quantity + "<br>" + "Delivery?:" + delivery;
$("#info").html(info);
}
</script>
</head>
<body>
<h1>Example page</h1>
<form onsubmit="displayInfo(); return false;">
<p>Enter the name of the product you want to buy: <input type="text" id="productName"/></p>
<p>Enter the quantity you want to buy: <input type="text" id="qty" /></p>
<p>Do you require delivery? <input type="checkbox" id="delivery" value="y" /></p>
<p><input type="submit" value="Place order" /></p>
</form>
<div id ="info"></div>
</body>
</html>
并且
alert("Product name: " + product + "<br>" + "Quantity: " + quantity + "<br>" + "Delivery?:" + delivery);
解决方案
您可能jQuery
错误地设置了库的路径。此外,您需要delivery
在使用它的同一级别上声明。
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
function displayInfo() {
const product = ($('#productName').val());
const quantity = parseInt($('#qty').val());
let delivery = "Delivery not required";
if ($('#delivery')[0].checked){
delivery = "Delivery required";
}
const info = "Product name: " + product + "<br>" + "Quantity: " + quantity + "<br>" + "Delivery?: " + delivery;
$("#info").html(info);
}
</script>
</head>
<body>
<h1>Example page</h1>
<form onsubmit="displayInfo(); return false;">
<p>Enter the name of the product you want to buy: <input type="text" id="productName"/></p>
<p>Enter the quantity you want to buy: <input type="text" id="qty" /></p>
<p>Do you require delivery? <input type="checkbox" id="delivery" value="y" /></p>
<p><input type="submit" value="Place order" /></p>
</form>
<div id ="info"></div>
</body>
</html>
推荐阅读
- php - am 的 over() 子句错误计算基于 id 到 mysql 中下一个或上一个值的行
- deployment - 是否可以将应用程序从 udeploy 迁移到 xldeploy 环境?
- mysql - Mysql 过程语法更改为 Firebird 过程语法
- jenkins - Jenkins Blue Ocean 重试限时步骤,最多 n 次
- java - Selenium WebDriver:随机单击一行按钮
- javascript - 从axios回调后如何清除字段?
- android - getFilter() 在 RecyclerView 适配器中无法正常工作?
- airflow - 如何运行 Airflow DAG 特定次数?
- python-3.4 - ord() 函数或带有 Z3 Solver 的字符串的 ASCII 字符代码
- flutter - 颤动行mainAxisAlignment spaceBetween不工作