如何在脚本函数中使用表单的值

时间:2018-10-07 01:38:44

标签: javascript html

我正在尝试获取要在命令orderPizza()中使用的名称和数量所输入的数据,我对此感到很困惑

function orderPizza() {
  var x = document.form["PizzaForm.Cname"].value;
  var y = document.form["PizzaForm.qPizza"].value;
  var z = parseFloat(12.99);
  var totalPrice = y * z;
  alert("Name: " + x + "Quantity ordered: " + y);
  var answer = prompt("Would you like to place this order", " ");
  if (answer == '1') {
    document.write("Your order has been placed");
  } else if (answer == '2') {
    document.write("Your order has been cancelled");
  } else {
    document.write("Invalid Entey");
  }
}
<!DOCTYPE html>
<html>

<body>
  <form name="PizzaForm">
    Name: <input type="text" name="Cname"><br><br> Quantity of Pizza: <input type="text" name="qPizza"><br><br>
    <button type="button" value="Submit" onclick="orderPizza" />Sumbit
  </form>
</body>

2 个答案:

答案 0 :(得分:0)

使用getElementsByName方法,并将onclick设置为orderPizza()

function orderPizza() {
  var x = document.getElementsByName("Cname")[0].value;
var y = document.getElementsByName("qPizza")[0].value;
  var z = parseFloat(12.99);
  var totalPrice = y * z;
  alert("Name: " + x + "Quantity ordered: " + y);
  var answer = prompt("Would you like to place this order", " ");
  if (answer == '1') {
    document.write("Your order has been placed");
  } else if (answer == '2') {
    document.write("Your order has been cancelled");
  } else {
    document.write("Invalid Entey");
  }
}
<!DOCTYPE html>
<html>

<body>
  <form name="PizzaForm">
    Name: <input type="text" name="Cname"><br><br> Quantity of Pizza: <input type="text" name="qPizza"><br><br>
    <button type="button" value="Submit" onclick="orderPizza()" />Sumbit
  </form>
</body>

答案 1 :(得分:0)

这两行是错误的:

var x = document.form["PizzaForm.Cname"].value;
var y = document.form["PizzaForm.qPizza"].value;

您不能将表单和输入名称组合成一个属性。输入是表单对象的属性。

var x = document.form["PizzaForm"]["Cname"].value;
var y = document.form["PizzaForm"]["qPizza"].value;