我试图将表单上显示的totalCost设置为我的javaScript函数正在计算的内容。出于某种原因,当我尝试将其设置为计算值时,它不起作用,但是当我将其设置为字符串时它会发生变化。如何将表单值设置为我计算的值?请参阅注释,指出我尝试使用代码设置的字段。
<script type="text/javascript">
var totalCost;
function getPrice(bookCost)
{
var shippingCostIndex;
shippingCostIndex=document.getElementById("mySelect").selectedIndex;
var shippingCostOptions=document.getElementById("mySelect").options;
var shipDestination;
shipDestination=shippingCostOptions[shippingCostIndex].text
alert("shipping Location:"+shippingCostOptions[shippingCostIndex].text);
if(shipDestination=="Eastern")
{
totalCost = bookCost + Number(2);
document.pikeForm.totalCost.setAttribute("value",totalCost); //**totalCost doesn't set it but "hello" sets the form value here
}
}
</script>
</head>
<body>
<form name="pikeForm" id="pikeForm" action=".../form.pl" method="post">
<fieldset>
<legend>your location</legend>
<label >Please indicate your ship destination in US.<br>
<select name="mySelect" id="mySelect" size="3" >
<option >Western</option>
<option >Eastern</option>
<option >Central</option>
</select>
</fieldset>
<input type="button" value="priceShipCalculator" onclick="getPrice(10)">
<br><br>
<fieldset>
<legend>order of Pike Book</legend>
<label for="pikeBook" >We will await your payment of $10 plus shipping and handling according to the above table for:<br>
<input id="pikeBook" value="Pike">How to Fillet a Pike</input><br>
<label for="totalCost"> Book Cost:
<input id="totalCost" name="totalCost" value="totalCost"></input> <!--**I want to set price to calculated price here-->
</fieldset>
</form>
</body>
我已经在线查看setAttribute,但它没有回答我的问题,因为我可以使用字符串设置值,但不能使用变量设置值。
答案 0 :(得分:2)
这里有几个问题,但首先要做的是:设置输入字段值的最短,最正确的方法是:
document.pikeForm.totalCost.value = totalCost;//assuming all the name properties are correct
但是我注意到你使用的各种奇怪的结构,可能是为了避免类型强制怪异。例如:
totalCost = bookCost + Number(2);
将值强制转换为给定类型可以以不同方式(更容易)完成:
totalCost = 2 + (+bookCost);//+varName coerces var's value to number
var asString = totalCost+'';//concatenate empty string, coerces to string
无需调用函数,更不用说兼作构造函数的函数
你也有一些奇怪的标记:
<input id="totalCost" name="totalCost" value="totalCost"></input>
我怀疑你的意思是:
<input type='text' id='totalCost' name='totalCost' value='default value'>
<!-- optionally close this tag using XML-style /> as in: <input _attributes here_ /> -->
其他琐事包括:
document.getElementById('mySelect')
连续两次,为什么?)尽管如此:
here's an alternative approach。它稍微复杂一些,但不受上面提到的问题的影响(没有全局变量,除了函数,没有冗余的DOM查询,没有标记中的JS和错误检查)
答案 1 :(得分:1)
尝试document.pikeForm.totalCost.setAttribute("value",totalCost+"");
,+""
将您的值转换为字符串。