0
Hi, 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 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 tell the 'qnt', so the id won’t repeat, but in JS I couldn’t create a for or another type of loop to "track" the while ids in php.
I have the following doubt, how would I create this for in JS? I’ve tried everything, I’ve done up arrays and nothing.
Here’s my JS code:
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;
};
VLW CARA, SERIOUSLY. Well, my PHP I didn’t change much, I just put even my $i in all ids and Names, because previously I was only counting in Quantity; From your Javascript I managed to do the calculation, thanks same guy! Your JS saved me, your HTML code too! It was only a matter of changing my PHP code, as you said yourself, THANKS GUY!
– Igo Brasil
Just one more question, how would I show the GENERAL TOTAL of these products (ie all totals summed) in a DIV out of the while?
– Igo Brasil
@Igo Brasil ready put another function that adds and generates a total.
– SK15