Add Select Multiple values

Asked

Viewed 974 times

2

I got the following select:

<select name="idservico[]" id="idservico">
<option data-valor="25,00" value="1">opção 1</option>
<option data-valor="20,00" value="1">opção 2</option>
</select>

I got the following input:

<input type="text" name="valor" id="valor"/>

I got the following script:

<script>
jQuery(document).ready(function () {
    jQuery('#idservico').change(function() {

jQuery('#valor').val((jQuery(this).find(':selected').data('valor')));
    });
});
</script>

So come on, when I select a service it sends the value of the service to the input, but I need that when selecting another service - because my select is multiple - it would have to add the value of the first selected to the second.

Can anyone help me? Be able to do until selecting and sending the value to the input, but add nothing so far. Grateful.

4 answers

1

A way to add up the values of select keeping the format of the comma values in the options:

With pure Javascript

document.addEventListener("DOMContentLoaded",()=>{
   document.querySelector("#idservico").addEventListener("change",(e)=>{
      let total = 0;
      for(let x of e.target.options){
         let val = parseFloat(x.dataset.valor.replace(',','.'));
         total += x.selected ? val : 0;
      }
      document.querySelector("#valor").value = total.toFixed(2).replace('.',',');
   });
});
<select name="idservico[]" id="idservico" multiple>
  <option data-valor="25,00" value="1">opção 1</option>
  <option data-valor="20,00" value="1">opção 2</option>
  <option data-valor="10,50" value="1">opção 3</option>
  <option data-valor="1250,50" value="1">opção 4</option>
</select>
<input type="text" name="valor" id="valor"/>

With jQuery

$(document).ready(function(){
   $("#idservico").on("change",function(){
      let total = 0;
      for(let x of $(this)[0].options){
         let val = parseFloat($(x).data("valor").replace(',','.'));
         total += $(x).is(":selected") ? val : 0;
      }
      $("#valor").val(total.toFixed(2).replace('.',','));
   });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="idservico[]" id="idservico" multiple>
  <option data-valor="25,00" value="1">opção 1</option>
  <option data-valor="20,00" value="1">opção 2</option>
  <option data-valor="10,50" value="1">opção 3</option>
  <option data-valor="1250,50" value="1">opção 4</option>
</select>
<input type="text" name="valor" id="valor"/>

0

It turns out that this way you’re not adding up, you’re just taking the value of select and adding to input.

Here’s an example that might help.

jQuery(document).ready(function() {
    jQuery('select[name="idservico[]"]').change(function() {

        let selects = jQuery("select[name=\"idservico[]\"]");
        let valorDoSelect = 0;
        
        /* Captura e soma o valor de todos os select */
        $(selects).map(function(i, e) {
          valorDoSelect += parseFloat( $(e).find(':selected').data('valor').toString().replace(",", ".") );
        });
    
        /* Exibe o valor */
        $('#valor').val( valorDoSelect )
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select name="idservico[]" id="idservico">
  <option data-valor="0" value="1">Selecione uma opção</option>
  <option data-valor="25,00" value="2">opção 1 (R$ 25,00)</option>
  <option data-valor="20,00" value="3">opção 2 (R$ 20,00)</option>
</select>

<select name="idservico[]" id="idservico2">
  <option data-valor="0" value="4">Selecione uma opção</option>
  <option data-valor="50,00" value="5">opção 3 (R$ 50,00)</option>
  <option data-valor="40,00" value="6">opção 4 (R$ 40,00)</option>
</select>


<input type="text" name="valor" id="valor" readonly />

or

jQuery(document).ready(function() {
    jQuery('select[name="idservico[]"]').change(function() {

        let selects = jQuery("select[name=\"idservico[]\"]");
        let total = 0;
        
        /* Percorre todos os select */
        $(selects).map(function(i, e) {
          let values = $(e).find(":selected");
        
          /* Percorre todos os valores selecionados */
          $(values).map(function(k, j) {
            total += parseFloat( $(j).data('valor').replace(",", ".") );
          });
        });
        
        $("#valor").val(total);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select name="idservico[]" id="idservico" multiple>
  <option data-valor="25,00" value="1">opção 1 (R$ 25,00)</option>
  <option data-valor="20,00" value="2">opção 2 (R$ 20,00)</option>
  <option data-valor="50,00" value="3">opção 3 (R$ 50,00)</option>
  <option data-valor="40,00" value="4">opção 4 (R$ 40,00)</option>
</select>

<select name="idservico[]" id="idservico" multiple>
  <option data-valor="1,00" value="1">opção 5 (R$ 1,00)</option>
  <option data-valor="2,00" value="2">opção 6 (R$ 2,00)</option>
  <option data-valor="3,00" value="3">opção 7 (R$ 3,00)</option>
  <option data-valor="4,00" value="4">opção 8 (R$ 4,00)</option>
</select>

<input type="text" name="valor" id="valor" readonly />

When working with coins, avoid using a comma (Ex: 25.00) to separate decimals, always use points (Ex: 25.00).

  • It’s adding up the value, but if I take an item from the selection it adds up too and could not.

  • @Lucianocoelhopettersen changed the code. If possible take a look.

0

Follow an example:

$(document).ready(function () {
    $('#idservico').change(function() {
      var total = 0;
      $(this).find(':selected').each(function(i){
        total += parseFloat($(this).data('valor'));      
      });
      $('#valor').val(total.toFixed(2));
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="idservico[]" id="idservico" multiple>
  <option data-valor="25.50" value="1">opção 1</option>
  <option data-valor="20.00" value="1">opção 2</option>
  <option data-valor="20.00" value="1">opção 3</option>
  <option data-valor="20.00" value="1">opção 4</option>
</select>
Tenho o seguinte input:
<input type="text" name="valor" id="valor"/>
Tenho o seguinte ajax:

  • this was perfect, only this rounding the sample pennies 25.50 + 30.00 is getting 55.00

  • You need to replace "," with "." as this is how Javascript recognizes decimals.

  • Right, it worked the way I wanted it. Thank you very much. Good afternoon

  • I found another problem, if the value is 1.125,50 it puts the value to 1.13 what would be the correct way to format?

  • Either you add the treatments to work with currency values or you use the pure value... in case it would be 1125.50

  • blz, got it, thanks

Show 1 more comment

0

select provides an array so vc te that add member to member of the array a simple way would be like this:

$(document).ready(function(){
console.log("teste")
  $("select").change(function(){
    var soma = 0;
    $(this).find(":selected").each(function(id,element){
    console.log(element)
      soma = soma + parseFloat($(element).data("value"))
    })
    
    $("span").text(soma)
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select name="cars" multiple>
  <option data-value="50.00" value="1">Volvo</option>
  <option data-value="52.25" value="2">Saab</option>
  <option data-value="55.75" value="3">Opel</option>
  <option data-value="58.00" value="5">Audi</option>
</select>
<p>Hold down the Ctrl (windows) / Command (Mac) button to select multiple options.</p>

<p>soma = <span></span></p>

</form>

go here

  • This is adding up the valeu and not the date containing the values

  • @Lucianocoelhopettersen I edited and put to pick the date

Browser other questions tagged

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