简体   繁体   English

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

[英]How do I use the value of the form in the script function

I am trying to get the data that is being inputted at the name and the quantity to be used in the function orderPizza(), I am quite confused about how to do it 我正在尝试获取要在函数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> 

use getElementsByName method, and set onclick to orderPizza() 使用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> 

These two lines are wrong: 这两行是错误的:

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

You can't combine the form and input names into a single property like that. 您不能将表单和输入名称组合成一个属性。 The input is a property of the form object. 输入是表单对象的属性。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM