Calculate select field values from a form

Asked

Viewed 402 times

1

Good afternoon to all.

I need some help from you. 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 the result of this sum:

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

How can I do this with Jquery?

2 answers

2


Can make that way:

$('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>
<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>
    
    <input type="text" class="form-control" id="valorTotal" name="valorTotal" value="" >

You can run the code above and see the result.

  • was excellent... thank you very much!!!

  • Hi @Amandarj all right? If you solved your problem does not fail to mark as answer. Abs.

  • Yes, thank you very much @Ricardo !

1

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

Then you can merge everything into a string to show in 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: https://jsfiddle.net/ueL007m/

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: https://jsfiddle.net/ueoL007m/1/

  • Thank you @Sergio !

Browser other questions tagged

You are not signed in. Login or sign up in order to post.