1

现场演示

当我从下拉列表中选择一些东西('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);
}
4

2 回答 2

4

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

parseInt("")

结果不是数字

也许您应该在多选的第一个选项上添加 selected 。

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

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

于 2013-07-05T12:47:27.437 回答
1

您必须使用 selectedIndex 和 options 值:

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>标签中。

于 2013-07-05T13:24:36.160 回答