我正在尝试从文本表单获取输入(特别是数字/ float ),并将其分配给一个可以用来进行计算的变量。单击计算按钮时应将其分配给变量。
我正在使用 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;
}
问题是当输入没有值时,在页面加载时获取值。如果您仅在单击按钮后获取该值,请确保在尝试获取输入之前已设置了值。
关于javascript - 需要帮助从表单输入分配变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33180522/