JavaScript function for generic use

0

I have a simple javascript function that calculates the value of one field multiplied by the value of another and inserts 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 a parameter but I do not know how to enter the data correctly.

    
asked by anonymous 05.05.2017 / 23:04

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 usage:

multiplica('tab1');
    
05.05.2017 / 23:16