我有点迷失在这里。我拥有的是一个包含项目和价格的基本菜单,设置为表单中的表格。我有一个文本输入框,供用户输入一个值 - 想要的该项目的数量。
我想知道在用户单击计算按钮后如何使用输入文本框中输入的数据,以便我可以验证它并在方程式中使用它。如果用户想要该项目的“2”,我需要将该值带入我的函数中,以便我可以将其验证为数值。然后,我将使用它作为整数,将其乘以与该商品相关的价格...
这是我的代码示例:
function calculate(){
var error = false;
if (isNaN(*"what would I put here??"*){
alert("A numeric value is required when ordering steak");
error = true;
}
else{
var numbercrabcakes = parseInt(-------);
}
if (!error)
{
total = numbercrabcakes * 15 * 1.0825;
window.alert("Your order totals: " + total.toFixed(2))
}
}
.........
<form name="myform">
<script type="text/javascript">
/* <![CDATA[ */
document.write("<table border = '1'>")
document.write("<tr><th>Item Picture</th><th>Item Description</th><th>Item Price</th> \
<th>Quanity</tr>");
document.write("<tr><td><img src = 'images/crabcakes.png'></td><td>Cirtus infused crab \
cakes with a sweet and savory sauce</td><td>$" + price[0] + "</td> \
<td><input type='text' id='crabcakes' size='10' value='0' style='text-align:right;' /></td>
</tr>");
/* ]]> */
</script>
<p id="submit_button"><input type="submit" value="Calculate" onclick="calculate()" \
style="width:150px;height:30px;text-align:center;font-weight:bold;" /></p>
</form>
代码的功能部分作为示例/指南给出,供我们的特定页面使用和编辑。我是否需要为输入框提供 id
或 name
并使用 getElementbyId
以便我可以根据 isNaN
检查它> 然后使用 parseInt
将其转换为函数所示。我确实尝试过,但它似乎对我不起作用。
最佳答案
如果您只想访问 ID 为“crabcakes”的文本框的值,您可以这样做:
function calculate(){
var value = document.getElementById("crabcakes").value;
var error = false;
if (isNaN(value)){
alert("A numeric value is required when ordering steak");
error = true;
}
else{
var numbercrabcakes = parseInt(value);
}
if (!error)
{
total = numbercrabcakes * 15 * 1.0825;
window.alert("Your order totals: " + total.toFixed(2))
}
}
关于javascript - 函数、表单和用户输入的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27374352/