Calculate using jQuery filled fields

Asked

Viewed 28 times

1

I have the following fields:

moeda, taxa_compra, taxa_venda, valor_reais, valor_total

I need you, when filling in the sales fee, to calculate:

taxa_venda / valor_reais e represente o total no valor_total.

How can I mount a jquery to do this?

1 answer

1


How can I mount a jquery to do this?

You can use a Event Handler of the kind input or blur, for example:

$("seletor_do_campo_taxa_de_venda").on("input ou blur", function(){
   // ação
});

The input will perform action as some value is inserted or removed from the field; the blur when the field loses the phocus (the cursor leaves the field).

To carry out the division taxa_sale / real value_real the values of both fields must be of the number. If fields are of type text, you have to convert them to number.

To play the value on the field total value, put in action the result of the division:

// se os campos forem tipo number
$("seletor_do_campo_taxa_de_denda").on("input ou blur", function(){
   var total = $("seletor_do_campo_taxa_de_venda").val() / $("seletor_do_campo_valor_total").val();
   $("seletor_do_campo_valor_total").val(total);
});

or

// se os campos forem tipo text com decimais separados por vírgula
$("seletor_do_campo_taxa_de_venda").on("input ou blur", function(){
    var tx_venda = parseFloat($("seletor_do_campo_taxa_de_venda").val().replace(".","").replace(",","."));
    var vl_total = parseFloat($("seletor_do_campo_valor_total").val().replace(".","").replace(",","."));
    var total = tx_venda / vl_total;
    $("seletor_do_campo_valor_total").val(total);
});

Obs.: if the element representing the total value be a div, change $("seletor_do_campo_valor_total").val(total); for $("seletor_do_campo_valor_total").text(total);

Browser other questions tagged

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