如果仅选中一项,如何求和多个选定项的值。从示例中,我想获取“ X12SO + X13SO = 30”的值
let sum = 0;
$("select[name='myselect[]'] option").each(function(){
sum += +this.value.split("|")[1];
});
$("input[name='myresult']").val(sum);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple class="form-control" id="multipleSelect" name="myselect[]">
<option value="X12SO|10">X12SO</option>
<option value="X13SO|20">X13SO</option>
<option value="X14SO|30">X14SO</option>
<option value="X15SO|40">X15SO</option>
<option value="X16SO|50">X16SO</option>
</select>
<input type="text" name="myresult">
答案 0 :(得分:1)
使用onchange
检测所选选项是否更改。
let sum = 0;
$("#multipleSelect").on("change", function(){
sum = 0;
// if there are no options being selected, it would be an empty array[]
// and sum each splited value
($(this).val() || []).map(v=>sum += +v.split("|")[1])
$("input").val(sum);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple class="form-control" id="multipleSelect" name="myselect[]">
<option value="X12SO|10">X12SO</option>
<option value="X13SO|20">X13SO</option>
<option value="X14SO|30">X14SO</option>
<option value="X15SO|40">X15SO</option>
<option value="X16SO|50">X16SO</option>
</select>
<input type="text" name="myresult">