2013-08-02 44 views
0

我试图创建一个代码,它会询问用户有多少项X,Y等,并使用Javascript来计算所欠的总数以及打印总结(收据)购买的所有物品。对不起noob问题,试图在没有任何正式培训的情况下学习代码。感谢所有的帮助!如何从HTML表单传入输入变量

<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> 
+0

那么问题是什么?你说你想做点什么,并且你看到它的代码来做上述的事情。所以有什么问题? – user1

回答

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 < 9上不支持,它使用innerText代替。在这种情况下,直接将消息直接写入innerHTML也是可行的,但这是一种坏习惯,因为与用户输入一起使用时会导致HTML注入安全漏洞。)