如何创建一个表单来验证输入并执行乘法运算

How can I create a form to validate inputs and perform a multiplication?

本文关键字:验证 输入 执行 运算 一个 何创建 创建 表单      更新时间:2023-09-26

上课时我缺席了,我的书没什么用我还没有学会如何制作按钮,也不知道如何完成这项任务。感谢您的帮助。请注意:我是一个初学者,这是一个介绍课,所以请保持简单!

  1. 两个输入框,一个用于接受商品的价格,另一个用于接收要订购的商品数量。

  2. 一个按钮来计算总数。

  3. 使用警告消息告诉他们总价或输入数据无效。

  4. 使用函数验证商品的价格和数量是否为数字。

  5. 一旦数据有效,请使用一个接受两个参数的函数,一个用于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>
  1. 两个输入框(a)用于价格,(b)用于数量

Price: <input name="price" id="price" value="" /><br />

Quantity: <input name="quantity" id="quantity" value="" />

  1. 一键计算总数

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" />

  1. 使用警告消息告诉他们总价或输入数据无效。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>