如何创建一个表单来验证输入并执行乘法运算
How can I create a form to validate inputs and perform a multiplication?
上课时我缺席了,我的书没什么用我还没有学会如何制作按钮,也不知道如何完成这项任务。感谢您的帮助。请注意:我是一个初学者,这是一个介绍课,所以请保持简单!
-
两个输入框,一个用于接受商品的价格,另一个用于接收要订购的商品数量。
-
一个按钮来计算总数。
-
使用警告消息告诉他们总价或输入数据无效。
-
使用函数验证商品的价格和数量是否为数字。
-
一旦数据有效,请使用一个接受两个参数的函数,一个用于price,另一个用于对于项目数,计算总额,然后显示总价。
我的代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Lab 8b: Stephanie Hussar</title>
<script type="text/javascript">
// Input
itemPrice = Number(prompt("Please enter the price of the item."));
itemQuantity = Number(prompt("Please enter the quantity of the items"));
total = itemPrice * itemQuantity
</script>
</head>
<body>
</body>
</html>
好吧,所以看起来您当前的实现与赋值不匹配。在我看来,你需要输入字段,然后点击一个按钮,所以让我们从这个开始:
输入字段:<input type="text" name="item_price" id="id_item_price" />
这将创建一个具有表单名称item price
和id id_item_price
的文本输入。
按钮:<input type="button" name="item_submit" id="id_item_submit" value="Calculate!" />
这将创建一个按钮,允许我们提交。我将其保留为type="button"
而不是type="submit"
,因为我在JavaScript中处理此问题,不想将表单提交到另一个网页。
把这些放在一起,我们就有了HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>My JavaScript</title>
<script type="text/javascript">
// TO DO: The Script!
</script>
</head>
<body>
<b>Enter the Item Price:</b><br />
<input type="text" name="item_price" id="id_item_price" />
<br /><br />
<b>Enter the Item Quantity:</b><br />
<input type="text" name="item_quantity" id="id_item_quantity" />
<br /><br />
<input type="button" name="item_submit" id="id_item_submit" value="Calculate!" />
</body>
</html>
添加计算
现在我们有了HTML,我们必须查看脚本。这里有几个概念需要注意。
按下按钮时执行代码
HTML允许我们指定与元素交互时会发生什么。一个这样的工具被称为onclick
。通过将我们的按钮HTML更改为以下内容,我们可以在单击按钮时调用JavaScript函数doCalculations()
!
<input type="button" name="item_submit" id="id_item_submit" value="Calculate" onclick="doCalculations()" />
既然我们已经完成了,让我们看看doCalculations()是什么样子的。
"进行计算"
我们还没有时间进行验证,但为了确保一切正常,我们想检查一些概念。
首先是从HTML文档中获取实际的文本字段。还记得之前我们说过商品价格的ID为id_item_price
吗?事实证明,这将帮助我们现在用这段代码访问它:
itemPrice = document.getElementById( 'id_item_price' );
这将创建一个名为itemPrice
的新变量。然后,我们使用JavaScript的getElementById()
函数获取对该特定文本字段的引用。使用相同的方法,我们可以获得数量(如果我们想的话,甚至可以获得按钮!):
itemQuantity = document.getElementById( 'id_item_quantity' );
现在我们有了表单字段,我们需要实际进行计算。等等:我们有个小问题。我们在变量中存储了对这些输入字段的引用,但没有实际值,只有字段。不用担心,JavaScript让我们很容易做到:
<Field>.value
给我们一个特定字段的值。所以,把这些放在一起,我们可以通过做itemPrice.value
得到itemPrice的值。
现在我们可以获取这些值,让我们进行实际计算,并将其存储在一个名为myTotal
:的变量中
myTotal = itemPrice.value * itemQuantity.value;
现在doCalculations中剩下的就是输出结果。你知道怎么做!你已经是职业选手了:
alert( "The total cost is: " + myTotal + "!" );
。
但是,哦,啪!如果有人在其中一个字段中键入"apples"而不是数字,该怎么办。看来我们必须进行验证。
验证
这一个有点棘手,所以请听我说。我们需要首先创建一个函数来验证我们的输入。为此,我们将使用两个JavaScript函数。如果你不理解我在这里的解释,请务必在网上查找,这样你才能完全理解。
如果JavaScript为myNumber参数找到NaN值,isNan( myNumber )
将返回true。
如果JavaScript能够将该条目值转换为浮点数,则parseFloat( myNumber )
将返回一个数字。如果不能,它将返回NaN。
如果一个数字是有限的合法数字,isFinite
将返回true。否则为False。
结合这些,我们可以检查输入的数字是否是实际数字:
function verifyNumber( myInput ){
if( !isNaN( parseFloat( myInput.value ) ) && isFinite( myInput.value ) )
return true;
else
return false;
}
ProTip:回想一下&&
是一个逻辑AND。当且仅当两个函数的结果都为true时,它才会返回true。否则将返回false。
所以现在让我们把它放进我们的doCalculations示例中:
function doCalculations(){
itemPrice = document.getElementById( 'id_item_price' );
itemQuantity = document.getElementById( 'id_item_quantity' );
// Add in the validations:
if( !verifyNumber( itemPrice ) || !verifyNumber( itemQuantity ) ){
alert( "One or both of your numbers is incorrect! Please enter a real number." );
return false;
}
myTotal = itemPrice.value * itemQuantity.value;
alert( "The total cost is: " + myTotal + "!" );
}
总结一下,这是我们的最终代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>My JavaScript</title>
<script type="text/javascript">
// Function: Verify that the input is an item number
function verifyNumber( myInput ){
if( !isNaN( parseFloat( myInput.value ) ) && isFinite( myInput.value ) )
return true;
else
return false;
}
function doCalculations(){
itemPrice = document.getElementById( 'id_item_price' );
itemQuantity = document.getElementById( 'id_item_quantity' );
// Add in the validations:
if( !verifyNumber( itemPrice ) || !verifyNumber( itemQuantity ) ){
alert( "One or both of your numbers is incorrect! Please enter a real number." );
return false;
}
myTotal = itemPrice.value * itemQuantity.value;
alert( "The total cost is: " + myTotal + "!" );
}
</script>
</head>
<body>
<b>Enter the Item Price:</b><br />
<input type="text" name="item_price" id="id_item_price" />
<br /><br />
<b>Enter the Item Quantity:</b><br />
<input type="text" name="item_quantity" id="id_item_quantity" />
<br /><br />
<input type="button" name="item_submit" id="id_item_submit" value="Calculate" onclick="doCalculations()" />
</body>
</html>
- 两个输入框(a)用于价格,(b)用于数量
Price: <input name="price" id="price" value="" /><br />
Quantity: <input name="quantity" id="quantity" value="" />
- 一键计算总数
Price: <input name="price" id="price" value="" /><br />
Quantity: <input name="quantity" id="quantity" value="" /><br />
<input type="submit" name="submit" value="Total" id="get-total" />
- 使用警告消息告诉他们总价或输入数据无效。i) 假设我们需要一个函数
function calculate_total (price, quantity) { var valid = false; var total = 0; var the_price = 0; var the_quantity = 0; // what constitutes a valid price? if(price && 0 < parseFloat(price)) { // perhaps? the_price = parseFloat(price); } if(quantity && 0 < parseInt(quantity)) { // perhaps? the_quantity = parseInt(quantity); } if(the_price > 0 && the_quantity > 0) { valid = true; // yay! we can continue :) // do any other things you want to do here } if(true === valid) { total = the_price * the_quantity; } return total; }
ii)好的,现在我们有了一个函数,我们该怎么处理它?-当我们点击提交按钮时,我们称之为,这样它就会计算出来
document.getElementById('get-total').onclick = function() {
var price = document.getElementById('price').value;
var quantity = document.getElementById('quantity').value;
alert(calculate_total(price,quantity)); // this alerts for (3)
return false; // stop the form being submitted
};
4) 这是由上面的步骤完成的,现在是5
把它放在一起:
<!doctype html>
<html>
<head>
<title>Lab 8b: Stephanie Hussar</title>
</head>
<body>
<p>
Price: <input name="price" id="price" value="" /><br />
Quantity: <input name="quantity" id="quantity" value="" /><br />
<input type="submit" name="submit" value="Total" id="get-total" />
</p>
<script>
// function to calculate the total from the price and quantity
// and do basic (very very basic) validation on inputs
function calculate_total (price, quantity) {
var valid = false;
var total = 0;
var the_price = 0;
var the_quantity = 0;
// what constitutes a valid price?
if(price && 0 < parseFloat(price)) { // perhaps?
the_price = parseFloat(price);
}
if(quantity && 0 < parseInt(quantity)) { // perhaps?
the_quantity = parseInt(quantity);
}
if(the_price > 0 && the_quantity > 0) {
valid = true; // yay! we can continue :)
// do any other things you want to do here
}
if(true === valid) {
total = the_price * the_quantity;
}
return total;
}
// add click event to the button
document.getElementById('get-total').onclick = function() {
var price = document.getElementById('price').value;
var quantity = document.getElementById('quantity').value;
alert(calculate_total(price,quantity)); // this alerts for (3)
return false; // stop the form being submitted
};
</script>
</body>
</html>
我到:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Lab 8b: Stephanie Hussar</title>
<script type="text/javascript">
function isValid() {
var price = document.getElementById('price').value;
var items = document.getElementById('items').value;
if (items=="" || price=="") {
alert('Price and quantity is required!');
}else if (isNaN(price) || isNaN(items)) {
alert('Numbers only!');
}else{
calculate(price, items);
}
}
function calculate(price, item) {
var result = document.createTextNode('The total is: '+price*item);
var form = document.getElementById('buy');
form.appendChild(result);
}
</script>
</head>
<body>
<form id="buy">
<label for="price">Price:</label>
<input id="price" />
<br />
<label for="items">Quantity:</label>
<input id="items" />
<br /><br />
<input type="button" value="Calculate" onclick="isValid();"/>
</form>
</body>
</html>
示例
简单问题的简单解决方案:
<input id=price type=text>
<input id=quantity type=text>
<input id=but type=button value=calculate onclick="document.getElementById('output').value=document.getElementById('price').value*document.getElementById('quantity').value">
<br><input id=output type=text>
- Angular2 Javascript 验证 输入数字而不是字符
- 在 Angular2 中构建多部分/表单数据 POST 请求并验证输入类型文件
- 如何通过 JavaScript 验证输入字段中的值
- jQuery 验证输入文本是否仅接受数字、单词或日期
- 如何javascript验证<输入类型=文件多个>如果浏览器不支持多个
- 用于验证输入的JavaScript正则表达式超过0个字符
- 验证输入字段和块字符
- Angularjs iu.mask带有日期的验证输入
- 验证输入,更新<td>属性以匹配验证状态
- 通过点击表单外的按钮,使用required和angularjs验证输入字段
- 基于自身输入变化的角度验证输入
- 使用 javascript 验证输入数组
- 年龄验证输入框 - 计算是否超过 18 岁
- JQuery 验证输入类型文件在服务器端失败
- 如何使用jquery或javascript验证输入框的内容
- JSF 和 RichFaces 用于实时验证输入框
- Javascript/Jquery:使用数字范围验证输入
- 如何在更改时验证输入字段并启用提交按钮
- 编码器点火器未验证输入文本
- 在复选框选择后验证输入类型文本