我正在尝试将表单上显示的总成本设置为我的 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在线,但它没有回答我的问题,因为我可以使用字符串设置值,但不能使用变量设置值。
最佳答案
这里有几个问题,但首先要注意的是:设置输入字段值的最短且正确的方法是这样的:
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_ /> -->
其他问题包括:
- 全局变量是邪恶
- 冗余 DOM 查询(
document.getElementById('mySelect')
连续两次,为什么?) - 标记中的 JS 格式不正确
- 不处理错误,例如:未选择任何值
无论如何:
Basic fiddle example
和here's an alternative approach 。它稍微复杂一些,但不受我上面提到的问题的影响(没有全局变量,除了函数之外,没有多余的 DOM 查询,标记中没有 JS,以及错误检查)
关于javascript - 如何将表单输入属性设置为计算的全局变量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24936399/