Problems with nextElementSibling when calculating a total - Jquery

1

I am trying to make a multiplication between quantity and price, to get your total, however I get the following error when doing it: TypeError: $(...).nextElementSibling is not a function , I do not know in what way I could modify it in such a way that it is acceptable, I share my code:

form

<form>
    <input type="text" id="quantity">
    <input type="text" id="price">
    <input type="text" class="result">
</form>

script

<script>
    $('#quantity, #price').keyup(function(){
        var cant = parseFloat(this.nextElementSibling('#quantity').val()) || 0;
        var price = parseFloat(this.nextElementSibling('#price').val()) || 0;
        var result = cant * price
        this.nextElementSibling('.result').val(result);
    })
</script>
    
asked by Hector Hernandez 16.08.2018 в 18:13
source

1 answer

1

You could search for items using $('selector') of jquery, like this:

$('#quantity, #price').keyup(function() {
  var cant = parseFloat($('#quantity').val()) || 0;
  var price = parseFloat($('#price').val()) || 0;
  var result = cant * price
  $('.result').val(result);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <input type="text" id="quantity"><br>
  <input type="text" id="price"><br>
  <input type="text" class="result">
</form>

nextElementSibling would work if you do something like document.getElementById("quantity").nextElementSibling but I would select the brother of quantity , which is price and I do not think it's very practical to use it that way, even in the case of the code that I hit the brother would be <br> .

If you want to multiply dynamically added items, you can use classes instead of ids:

$('.multi').keyup(function() {

  var precio = [];
  var cantidad = [];

  $('.precio').each(function(i, obj) {
    precio.push(+obj.value);
  });

  $('.cantidad').each(function(i, obj) {
    cantidad.push(+obj.value);
  });

  var resultado = 0;

  precio.map((o, i) => {
    resultado += o * cantidad[i];
  });

  $("#result").val(resultado);

})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <input type="text" class="multi precio"> precio<br>
  <input type="text" class="multi cantidad"> cantidad<br><br>
  <input type="text" class="multi precio"> precio<br>
  <input type="text" class="multi cantidad">cantidad<br><br>
  <input type="text" class="multi precio"> precio<br>
  <input type="text" class="multi cantidad">cantidad<br><br>
  <input type="text" class="multi precio"> precio<br>
  <input type="text" class="multi cantidad">cantidad<br><br><br>
  <input type="text" id="result">resultado
</form>
    
answered by 16.08.2018 / 18:21
source