Hello, I need your help;
I have my While in PHP listing all the materials, their quantities and a space where the Total is calculated as the quantity of the product increases.
Here's my PHP:
<?php
$dadosMaterial = mysql_query(carregaDados2());
$i = 1;
if (mysql_num_rows($dadosMaterial)>0) {
while($linha = mysql_fetch_array($dadosMaterial)){
echo "<br><label>".$linha['matnome']."</label>";
echo "<br>";
echo "<div id=px1>"."Valor"."<input type='text' class='form-control' style='width: 115px' value=".$linha['matpreco']." readonly='readonly' name='valor_unitario' id='valor_unitario'/>"."</div>";
echo "<div id=px2>"."Quantidade"."<input type='number' min='0' max=".$linha['matqtde']." class='form-control' style='width: 115px' name='qnt".$i."' id='qnt".$i."' value='0'/>"."</div>";
echo "<div id=px3>"."Total "."<input type='text' class='form-control' style='width: 115px' name='total' id='total' readonly='readonly'/></div>"."";
$i++;
}
}
?>
I created a variable to count 'qnt', so the id does not repeat itself, but in JS I could not create a for loop or other type of loop to 'follow' the while ids in php. >
I have the following question, how would I create this for in JS? I've tried everything, made up arrays and nothing.
Here's my code in JS:
function id(el) {
return document.getElementById( el );
}
function total( un, qnt ) {
return parseFloat(un.replace(',', '.'), 10) * parseFloat(qnt.replace(',', '.'), 10);
}
window.onload = function() {
id('valor_unitario').addEventListener('keyup', function() {
var result = total( this.value , id('qnt1').value );
id('total').value = String(result.toFixed(2)).formatMoney();
});
id('qnt1').addEventListener('keyup', function(){
var result = total( id('valor_unitario').value , this.value );
id('total').value = String(result.toFixed(2)).formatMoney();
});
}
String.prototype.formatMoney = function() {
var v = this;
if(v.indexOf('.') === -1) {
v = v.replace(/([\d]+)/, "$1,00");
}
v = v.replace(/([\d]+)\.([\d]{1})$/, "$1,$20");
v = v.replace(/([\d]+)\.([\d]{2})$/, "$1,$2");
v = v.replace(/([\d]+)([\d]{3}),([\d]{2})$/, "$1.$2,$3");
return v;
};