TAGS :Viewed: 7 - Published at: a few seconds ago

[ Calculate multiple select dropdown ]

I have a multiple selection menu like so:

<select style="width:345px;" multiple="multiple" id="syndicate_group">
    <option data-cost="10" value="groupNo114">Starter</option>
    <option data-cost="15" value="groupNo100">Bronze</option>
    <option data-cost="25" value="groupNo104">Silver</option>
    <option data-cost="34" value="groupNo108">Gold</option>
    <option data-cost="0" value="groupNo115">Other</option>
</select>

<input type="number" placeholder="" value="" name="ammountToPay" id="ammountToPayField">

I want to do a calculation based on the data-cost and not the value of user selection, so if the user selects both Starter and Bronze, the value in the id of 'ammountToPayField' will be 25, but then if they decide they only want bronze, the value in 'ammountToPayField' will only be 15 but having looked for a while I can only find input fields and not a multiple select field.

Answer 1


Try this:

$('#syndicate_group').change(function() {
    var sum = $(this).find(':checked')
                     .map(function() { return parseInt($(this).data('cost'), 10); })
                     .get()
                     .reduce(function(x, y) { return x + y; });

    $('#ammountToPayField').val(sum);
});

See Fiddle

Answer 2


Try this:

$("#syndicate_group").change(function () {
var sum = 0;
$("select option:selected").each(function() {
  sum += parseInt($(this).text());
});
$( "#ammountToPayField" ).text( sum ); }).change();