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

标签 javascript html

我正在尝试从文本表单获取输入(特别是数字/ 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/

相关文章:

javascript - 如果 npm 工作正常,为什么还要使用 Bower.js?

javascript - 动态加载javascript文件后如何添加回调

javascript - 保证获取类实例的方法?

html - 将文本环绕在一个 div 周围

html - 调整窗口大小时菜单栏被截断

html - 如何使用 Bootstrap 将多张图片放在媒体对象的同一行?

javascript - 在 Backbone 中选中复选框时禁用输入字段

javascript - 如何使用 intro.js 突出显示 Bootstrap 模式

html - 将文件拖放到其中时,文件字段 "accept"属性无法正常工作

html - 如何在移动汉堡菜单中将 bootstrap 4 nav-item 元素并排放置?