Javascript function for generic use

Asked

Viewed 138 times

0

I have a simple javascript function that calculates the value of one field multiplied by the value of another and inserts it into a third. Below the code:

function multiplica() {
    var quantidade = parseFloat(document.getElementById("tab1quantidade").value);
    var aux = document.getElementById("tab1valor");
    var valor = parseFloat(aux.options[aux.selectedIndex].value);
    document.getElementById("tab1total").value = parseFloat(quantidade * valor).toFixed(2); 
}

The fields are as follows:

<td class="col-md-3">
  <input type="number" min="0" max="10" step="1" class="form-control text-center" name="bulletin['tab6quantidade']" id="tab6quantidade" value="0" onChange="multiplica();">
</td>

I need to use this same function for other fields but with different Ids. I have to pass the field ID as parameter but do not know how to enter the data correctly.

  • Shows more HTML and the relationships between the accounts you want to do.

1 answer

1


If I understood correctly, it would be this:

function multiplica(tabName) {
    var quantidade = parseFloat(document.getElementById(tabName + "quantidade").value);
    var aux = document.getElementById(tabName + "valor");
    var valor = parseFloat(aux.value);
    document.getElementById(tabName + "total").value = (quantidade * valor).toFixed(2); 
}

Example of use:

multiplica('tab1');

Browser other questions tagged

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