[英]Need help assigning variable from form input
我正在尝试从文本表单获取输入(特别是数字/浮点数),并将其分配给可用于计算的变量。 单击“计算”按钮时,应将其分配给变量。
我正在使用getElementById()为我返回未定义。
先前的研究指出,我需要在输入标签下方添加脚本标签。
所以我将脚本从head标签移动到body标签,但仍然遇到麻烦(仍然返回未定义的返回值)。
<form name = "myform">
Item Price <input type = "text" name = "tPrice">
<br><br>
<input type = "button" value = "Calculate" onClick = "calculate()"/>
<input type = "submit" value = "Submit"/>
<input type = "reset" value = "Clear"/>
</form>
<script>
var totalPrice = parseFloat(document.getElementById("tPrice").value);
//var totalPrice = document.getElementById("iPrice");
//var price = document.getElementById("price").value;
//document.getElementById("price").value = totalPrice;
//var shipMeth = document.getElementById("ship").checked;
function calculate()
{
//DISPLAY Results
window.alert(totalPrice);
//shipping and handling results
document.myform.sh.value = "500";
//tax
document.myform.tax.value = "500";
//total
document.myform.total.value = "500";
//window.alert(document.myform.sh.value);
window.alert("Results function successful")
return true;
}
</script>
输入需要一个ID属性,您可能希望将获取和解析值移至计算函数中。
Item Price <input type = "text" id = "tPrice">
和
function calculate()
{
var totalPrice = parseFloat(document.getElementById("tPrice").value);
//DISPLAY Results
window.alert(totalPrice);
//shipping and handling results
document.myform.sh.value = "500";
//tax
document.myform.tax.value = "500";
//total
document.myform.total.value = "500";
//window.alert(document.myform.sh.value);
window.alert("Results function successful")
return true;
}
问题是当输入没有值时,获取值将在页面加载时运行。 如果仅在单击按钮后才获得值,则在尝试获取输入之前,请确保已设置了该值。
您需要设置input id="tPrice"
而不是name
属性。 希望有帮助:)
更改
Item Price <input type = "text" name = "tPrice">
至
Item Price <input type = "text" id = "tPrice">
我将把getElementById调用移到calculate方法中,因为如果它是文本输入,则应在用户用值填充后才使用其值进行计算。 是的,将id添加到输入中,而不是name属性。 如果要在页面加载时立即保存输入的值,则应等待DOM准备就绪:
$(document).ready(function() { /* code here */ });
请注意,因为如果该值为空,则parseFloat将导致NaN。
将var
放入函数中,如下所示:
function calculate()
{
var totalPrice = parseFloat(document.getElementById("tPrice").value);
//DISPLAY Results
window.alert(totalPrice);
//shipping and handling results
document.myform.sh.value = "500";
//tax
document.myform.tax.value = "500";
//total
document.myform.total.value = "500";
//window.alert(document.myform.sh.value);
window.alert("Results function successful")
return true;
}
然后将id="tPrice"
添加到输入中,如下所示:
<input type = "text" name = "tPrice" id="tPrice">
并查看小提琴: http : //jsfiddle.net/vantbrhb/8/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.