Calculate select field values for a form

1

Good afternoon everyone.

I need your help. I have the following select multiple:

    <select id="precoFruta" multiple name="valores">
        <option value="1.5">Macã - R$1,20</option>
        <option value="2.5">Uva  - R$2,50</option>
        <option value="1.0">Limão- R$1,00</option>            
    </select>

As the user selects 1 or more fruits, another field is displayed as the result of this sum:

<input type="text" class="form-control" id="valorTotal" name="valorTotal" value="" >

How can I do this with JQuery?

    
asked by anonymous 28.09.2016 / 20:16

2 answers

2

You can do this:

$('select').change(function(){
    var sum = 0;
    $('select :selected').each(function() {
        sum += Number($(this).val());
    });
     $("#valorTotal").val(sum);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><selectid="precoFruta" multiple name="valores">
        <option value="1.5">Macã - R$1,20</option>
        <option value="2.5">Uva  - R$2,50</option>
        <option value="1.0">Limão- R$1,00</option>            
    </select>
    
    <input type="text" class="form-control" id="valorTotal" name="valorTotal" value="" >

You can run the above code and see the result.

    
28.09.2016 / 20:22
1

To get all the option selected you have to go one by one and get your value.

Then you can put everything together in a string to show in the input.

You can do it like this:

$('#precoFruta').on('change', function() {
    var values = $(this).find('option:selected').map(function() {
        return this.value;
    }).get().join(', ');
    $('#valorTotal').val(values);
});

jsFiddle: link

Se for caso de quereres a soma deles podes fazer assim:

$('#precoFruta').on('change', function() {
    var soma = $(this).find('option:selected').get().reduce(function(sum, el) {
        return sum + Number(el.value);
    }, 0);
    $('#valorTotal').val(soma);
});

jsFiddle: link

    
28.09.2016 / 20:21