我正在尝试使用jquesry添加几个下拉列表的值,如下所示:
$('select').change(function() {
var sum = 0;
var val1 = $("#Qty_0").val();
var val2 = $("#Qty_1").val();
var sum = parseInt(val1) + parseInt(val2);
$("#sum").html(sum);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="now" for="Qty_0">Quantity 1</label>
<select name="Qty[]" id="Qty_0"><option value="">Please select ...</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<label class="now" for="Qty_1">Quantity 1</label>
<select name="Qty[]" id="Qty_1"><option value="">Please select ...</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<div id=sum></div>
这总是使用||返回NaN错误0将这些设置为0以确认NaN错误,但如何使其工作?反正有没有在开发人员工具中看到teh var值?
答案 0 :(得分:2)
您可以利用||
并将变量的val1
和val2
的值设置为0
,当选择的值为false ""
时。
$('select').change(function() {
var sum = 0;
var val1 = $("#Qty_0").val() || 0;
var val2 = $("#Qty_1").val() || 0;
var sum = parseInt(val1, 10) + parseInt(val2, 10);
$("#sum").html(sum);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="now" for="Qty_0">Quantity 1</label>
<select name="Qty[]" id="Qty_0">
<option value="">Please select ...</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<label class="now" for="Qty_1">Quantity 2</label>
<select name="Qty[]" id="Qty_1">
<option value="">Please select ...</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<div id=sum></div>