user1338176
user1338176

Reputation: 105

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.

Upvotes: 1

Views: 349

Answers (2)

Jay
Jay

Reputation: 757

Try this:

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

Upvotes: 0

haim770
haim770

Reputation: 49135

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

Upvotes: 2

Related Questions