0

How can I sum the value of selected multiple item if only the item is selected. From the example I wanna get the value of "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">

1 Answer 1

1

Use onchange to detect if the selected options changed.

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">

Sign up to request clarification or add additional context in comments.

2 Comments

@Hikarunmemory, what is v in map
@whoami, each value of the selected options. If you select X12SO, v would be X12SO|10.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.