需要帮助从表单输入分配变量

Need help assigning variable from form input

本文关键字:输入 分配 变量 表单 帮助      更新时间:2023-09-26

我试图从文本形式获得输入(特别是数字/浮点数),并将其分配给一个变量,我可以用它来做计算。当计算按钮被点击时,它应该被赋值给变量。

我正在使用getElementById(),它为我返回未定义。

先前的研究指出,我需要在我的输入标签下面有我的脚本标签。

所以我把我的脚本从头部标签移动到正文标签,我仍然有问题(仍然得到未定义的返回)。

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

Input需要一个ID属性,您可能希望将值的获取和解析移到calculate函数中。

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调用移动到计算方法中,因为如果它是一个文本输入,您应该仅在用户用值填充它之后才计算其值。是的,在输入中添加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/