Add values after a separator

Asked

Viewed 37 times

0

Since I don’t know much about javascript I would like a little help to solve this problem of mine In this script below I have to do the calculation taking only the last digits separated by the hyphen -

value="10-banana-2,55" ==> só somar o  ( 2,55 ) depois do segundo traço 

id-nome-valor 

$(function() {
  total = document.getElementById('total');
  $(document.getElementsByName('choice')).bind('click', function() {

    var valTotal = total.value;

    valTotal = parseFloat(valTotal.replace(',', '.'));

    var valInput = (this.value);

    valInput = parseFloat(valInput.replace(',', '.'));

    var novoTotal = 0;
    var value = (this.checked) ? parseFloat((valTotal + valInput)).toFixed(2) : parseFloat((valTotal - valInput)).toFixed(2);
    total.value = value.replace('.', ',');
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>


<form name="listForm" id="listForm">
  <input type="checkbox" name="choice" value="10-banana-2,55" />2,55<br/>
  <input type="checkbox" name="choice" value="12-uva-3,00" />3,00<br/>
  <input type="checkbox" name="choice" value="13-pera-1,00" />1,00<br/>
  <input type="checkbox" name="choice" value="16-tmate-2,00" />2,00<br/>
  <input type="text" size="4" name="total" id="total" value="100,00" />
</form>

3 answers

1

You have to break that value into pieces but also convert strings 2,55 in Numbers with ..

Suggestion:

$(function() {
  function converterNumero(nr) {
    if (typeof nr === 'number') return nr;
    return Number(nr.replace(',', '.'));
  }

  var total = $('#total');
  var escolhas = $('[name="choice"]');
  escolhas.on('change', function() {

    var soma = escolhas.get().reduce(function(soma, el) {
      if (!el.checked) return soma;
      var nr = el.value.split('-').pop();
      var value = converterNumero(nr);

      return soma + value;
    }, Number(converterNumero(total.val())));
    total.val(soma);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>


<form name="listForm" id="listForm">
  <input type="checkbox" name="choice" value="10-banana-2,55" />2,55<br/>
  <input type="checkbox" name="choice" value="12-uva-3,00" />3,00<br/>
  <input type="checkbox" name="choice" value="13-pera-1,00" />1,00<br/>
  <input type="checkbox" name="choice" value="16-tmate-2,00" />2,00<br/>
  <input type="text" size="4" name="total" id="total" value="100,00" />
</form>

1


Using your script, not to complicate too much and you understand what happens, can do so

$(function() {
        total = document.getElementById('total');

        $(document.getElementsByName('choice')).bind('click', function() {

            var valTotal = total.value;

            valTotal = parseFloat(valTotal.replace(',', '.'));

            // Pega o valor selecionado e divide pelo '-', o resultado do split gera um array
            var valInput_split = (this.value).split('-');

            // Pega o último valor deste array, que no seu caso é o valor que você quer somar
            var valor_final = valInput_split[valInput_split.length-1];

            var valInput = parseFloat(valor_final.replace(',', '.'));

            var novoTotal = 0;
            var value = (this.checked) ? parseFloat((valTotal + valInput)).toFixed(2) : parseFloat((valTotal - valInput)).toFixed(2);
            total.value = value.replace('.', ',');
        });

    });

In summary, it is enough to exchange two lines

var valInput = (this.value);
valInput = parseFloat(valInput.replace(',', '.'));

For these three lines

var valInput_split = (this.value).split('-');
var valor_final = valInput_split[valInput_split.length-1];
var valInput = parseFloat(valor_final.replace(',', '.'));

1

Use no more .bind because it has become obsolete since the version 1.7 jQuery and was removed from version 3.0.

A hint to get the value is to use the method .replace(). Just use as a single argument .lastIndexOf("-")+1, i.e., it will take the first character after the last hyphen until the end of the string.

In the example below I replaced some pure JS methods with jQuery methods:

$(function() {
   var total = $('#total');
  $('[name=choice]').on('click', function(){

    var valTotal = total.val();

    valTotal = parseFloat(valTotal.replace(',', '.'));

    var valInput = this.value.substr(this.value.lastIndexOf("-")+1);

    valInput = parseFloat(valInput.replace(',', '.'));

    var novoTotal = 0;
    var value = (this.checked) ? parseFloat((valTotal + valInput)).toFixed(2) : parseFloat((valTotal - valInput)).toFixed(2);
    total.val(value.replace('.', ','));
  });

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<form name="listForm" id="listForm">
  <input type="checkbox" name="choice" value="10-banana-2,55" />2,55<br/>
  <input type="checkbox" name="choice" value="12-uva-3,00" />3,00<br/>
  <input type="checkbox" name="choice" value="13-pera-1,00" />1,00<br/>
  <input type="checkbox" name="choice" value="16-tmate-2,00" />2,00<br/>
  <input type="text" size="4" name="total" id="total" value="100,00" />
</form>

Browser other questions tagged

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