JavaScript:计算输入(选择输入)并生成数字

时间:2013-07-05 12:34:01

标签: javascript

LIVE DEMO

当我从下拉列表中选择某个内容时('room_type_id'和'bed_type_id'),它会输出一个“NaN”(非数字)。如果我首先从多个选择输入('bed_type_id')中选择一些内容,那么输出结果为:52000,53000,53500,尽管实际值为1000,2000,2500,您可以在上面的演示中的HTML表单中看到。

我怀疑parseInt与它有关。 parseFloat也不起作用。有什么建议吗?

function jungi() {
   var room_type_id=document.getElementById('room_type_id').value;
   var meal_type_id=document.getElementById('meal_type_id').value;
   var bed_type_id=document.getElementById('bed_type_id').value;
   document.getElementById('total_amount').value = parseInt(room_type_id) + parseInt(meal_type_id) + parseInt(bed_type_id);
}

2 个答案:

答案 0 :(得分:4)

您的多项选择在加载时未选择任何值,因此您尝试执行以下操作:

parseInt("")

结果为非数字

也许您应该在多重选择的第一个选项中添加所选。

<option value="1000" selected>Breakfast</option>

您还可以在调用parseInt之前检查空字符串

答案 1 :(得分:1)

您必须使用selectedIndex和选项值:

使用Javascript:

var room = document.getElementById("room_type_id");
var meal = document.getElementById("meal_type_id");
var bed = document.getElementById("bed_type_id");
document.getElementById("form1").onchange = jungi;
function jungi() {
 document.getElementById("total_amount").value = parseInt(room.options[room.selectedIndex].value) + parseInt(meal.options[meal.selectedIndex].value) + parseInt(bed.options[bed.selectedIndex].value);       
}

此外,您必须将选择标记包装到<form id = "form1">...</form>标记。