如何从HTML表单传递输入变量

时间:2013-08-02 13:22:45

标签: javascript html forms variables

我正在尝试创建一个代码,该代码会询问用户X,Y等项目的数量,并使用Javascript计算欠款总数,并打印所有购买商品的摘要(收据)。抱歉,在没有任何正式培训的情况下尝试学习代码。感谢您的帮助!

<html>

<head>

<title>Cost Calculator</title>

<script language="javascript" type="text/javascript">
function packageTotal(){
    //Enter in prices here
    var applePrice = 1;
    var bookPrice = 2;
    x = Number(document.calculator.books.value);
    y = Number(document.calculator.apples.value);
    var b = applePrice*x + bookPrice*y;
    var p = applePrice*x + bookPrice*y + .5;

    if (document.getElementById('noBag').checked) {
    //Basic package is checked
    document.calculator.total.value = b;
        } else if (document.getElementById('yesBag').checked) {
    //Pro package is checked
    document.calculator.total.value = p;
        }

    //Want to add summary of purchase
    //document.write("You want " + x " books and " y " apples.");


}

</head>

<body>

<!-- Opening a HTML Form. --> 
<form name="calculator">

<!-- Here user will enter the number of Books and Apples --> 
Enter Number of Books: <input type="text" name="books"> 
<br />

Enter the Number of Apples: <input type="text" name="apples">
<br />

<br />
<input type="radio" name="item" id="noBag" value="No" /> noBag
<input type="radio" name="item" id="yesBag" value="Yes" checked /> yesBag

<!-- Here result will be displayed. -->

<input type="button" value="Submit" onclick="packageTotal();">

Your Total Price is: <input type="text" name="total">

</form>


</body>
</html>

1 个答案:

答案 0 :(得分:1)

从问题中不清楚,但如果这是问题:

//Want to add summary of purchase
//document.write("You want " + x " books and " y " apples.");
然后那肯定会破裂。 document.write仅在文档仍在加载时添加到当前文档。如果您之后调用它,它将隐式打开要写入的新文档,从而破坏当前页面。通常document.write是件坏事。

(由于缺少+连接运算符,也存在微不足道的语法错误)

如果要将任意文本写入页面,请创建占位符元素:

<div id="message"></div>

然后设置其文本内容:

function setTextContent(element, text) {
    element.innerHTML = ''; // remove current content
    element.appendChild(document.createTextNode(text));
}

var message = document.getElementById('message');
setTextContent(message, 'You want '+x+' books and '+y+' apples.');

(元素上有一个textContent属性,您也可以使用它而不是函数,但IE&lt; 9上不支持使用innerText代替它。只需将消息直接写入{{ 1}}也适用于这种情况,但这是一个坏习惯,因为当与用户输入一起使用时会导致HTML注入安全漏洞。)