我有一个onchange多选选项,可以选择多个课程,然后显示其他输入值的总价格
但是,如果我在该输入中总结了几个月的另一个多选项,那么如何获得总价
每个月的价格相同
当然选择选项代码
<select class="form-control" onchange="selectFunction(event)"
name="pay_course[]" required="" multiple>
<option data-price="1111" value="courseId1">English</option>
<option data-price="2222" value="courseId2">Math</option>
</select>
月选择选项代码
<select class="form-control" multiple="multiple" >
<option selected="selected" value="" name="pay_fee_month[]" disabled="true">Select Month...</option>
<option value='Janaury'>Janaury</option>
<option value='February'>February</option>
<option value='March'>March</option>
<option value='April'>April</option>
<option value='May'>May</option>
<option value='June'>June</option>
<option value='July'>July</option>
<option value='August'>August</option>
<option value='September'>September</option>
<option value='October'>October</option>
<option value='November'>November</option>
<option value='December'>December</option>
</select>
输入显示总数
<input type="number" value="" id="money" class="form-control">
脚本
function selectFunction(e) {
var type_id = $('select option:selected').map(function() {
return $(this).attr('data-price');
})
.get().map(parseFloat).reduce(function(a, b) {
return a + b
});
console.log(type_id)
$("#money").val( type_id );
}
答案 0 :(得分:2)
我会以另一种方式做到......完全。
您希望拥有的是基于所选课程的总价格乘以所选月份的数量。
下面是一个脚本,它就是这样做的......在两个选择的$("#courses, #months").on("change", function(){
// Get the total price of the selected courses.
var price = 0;
$("#courses").find("option:selected").each(function(){
price += $(this).data("price");
});
console.log(price);
// Get the amount of selected months.
var monthCount = $("#months").find("option:selected").length;
console.log(monthCount);
// Multiply.
var total = monthCount * price;
$("#money").val(total);
});
上。
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control" id="courses" name="pay_course[]" required="" multiple>
<option data-price="1111" value="courseId1">English</option>
<option data-price="2222" value="courseId2">Math</option>
</select>
<select class="form-control" id="months" multiple="multiple" >
<option value="" name="pay_fee_month[]" disabled>Select Month...</option>
<option value='January'>January</option>
<option value='February'>February</option>
<option value='March'>March</option>
<option value='April'>April</option>
<option value='May'>May</option>
<option value='June'>June</option>
<option value='July'>July</option>
<option value='August'>August</option>
<option value='September'>September</option>
<option value='October'>October</option>
<option value='November'>November</option>
<option value='December'>December</option>
</select>
<input type="number" value="" id="money" class="form-control">
onchange
请注意,我删除了内联selected="selected"
处理程序并使用了jQuery .on()
我还删除了第一个月选项中的^(?!$)(?:[a-z]|[0-9]{0,2}(?![0-9])|[\-|_](?![\-|_]))*$
,因为它也被禁用了。