Differentiate inputs of two forms in JQuery or Javascript

0

I am developing a web application for a travel agency, in this application the sales are registered, these sales have services that vary the cost of each depending on the client, supplier and / or destination.
In the part where I add these sales I have a form where in several I have a function that captures the onKeyUp event of certain input and calculates the VAT, ish, final price, total markup of the sale, etc.
So far so good, my problem is that I want to add another form to edit that sale and I want to use that same function to not write another function specifically to edit the sale.

How can I differentiate the inputs that have the same name or class but that are of different forms?

    
asked by Fernando Ferretiz 17.02.2018 в 15:43
source

1 answer

1

You have different ways of doing it.

A simple one is to search among the parents of the control that generated the event the form to which it belongs. Once you locate the form you can find the rest of the controls that you want to use within the children of this one.

Here is an example with two equal forms with fields for price, quantity and total. Event keyup of the price and quantity fields launch a function that automatically calculates the total using the fields of the form in which the value is being edited:

$(function(){
  function calcularprecio(){
    var $form = $(this).parents('form');
    var $precio = $form.find('.precio');
    var $cantidad = $form.find('.cantidad');
    var precio = parseFloat($precio.val());
    var cantidad = parseFloat($cantidad.val());
    if (!isNaN(precio) && !isNaN(cantidad)){
      $form.find('.total').val(precio * cantidad);
    }
  }
  
  $('.precio,.cantidad').keyup(calcularprecio);
});
form{
  padding: 20px;
}
div{
  display: block;
  padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div>Precio <input type="number" class="precio"></div>
<div>Cantidad <input type="number" class="cantidad"></div>
<div>Total <input type="number" class="total"></div>
</form>
<form>
<div>Precio <input type="number" class="precio"></div>
<div>Cantidad <input type="number" class="cantidad"></div>
<div>Total <input type="number" class="total"></div>
</form>
    
answered by 17.02.2018 / 16:00
source