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

时间:2015-10-16 22:33:01

标签: javascript html

我试图从文本表单获取输入(特别是数字/浮点数),并将其分配给我可以用来进行计算的变量。单击计算按钮时,应将其分配给变量。

我正在使用getElementById(),它为我返回undefined。

之前的研究指出,我需要将我的脚本标记放在输入标记下面。

所以我将脚本从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>

5 个答案:

答案 0 :(得分:1)

输入需要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;
}

问题是当输入没有值时,在页面加载时运行值。如果只在单击按钮时获得该值,则在尝试获取之前确保输入已设置值。

答案 1 :(得分:0)

您需要设置input id="tPrice"而不是name属性。希望有所帮助:)

答案 2 :(得分:0)

更改

Item Price <input type = "text" name = "tPrice">

Item Price <input type = "text" id = "tPrice">

答案 3 :(得分:0)

我会将getElementById调用移动到calculate方法中,因为如果它是文本输入,则只有在用户用值填充后才能计算其值。是的,将id添加到输入而不是name属性。如果要在页面加载时立即保存输入值,则应等待DOM准备好:

    $(document).ready(function() { /* code here */ });

请注意,因为如果值为空,则parseFloat将产生NaN。

答案 4 :(得分:0)

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/

相关问题