teashark teashark - 1 month ago 12
Javascript Question

Get values from php loop and multiple those values on keyup

I have a PHP loop created dynamically with two text boxes and one result column.

What i need is , just multiple the values entering first two boxes and show result in its near Result box.

The PHP loop

<?php
$sql=$db->query("SELECT * FROM calc");
foreach($sql as $row)
{
?>
<div class="calc">
<input type="text" id="txt1id<?= $row['id'] ?>" onkeyup="multiple()">
<input type="text" id="txt2id<?= $row['id'] ?>" onkeyup="multiple()">
<input type="text" id="resultid<?= $row['id'] ?>" title="Result shows here automatically">
</div>
<?php } ?> // loop ends here.


And script is

<script>
function multiple()
{
// how to get two different variables like this with different id to multiple ?
var firstBox = parseInt(document.getElementById(firstid).value);
var secondBox = parseInt(document.getElementById(secondid).value);


}
</script>

Answer

Pass row id to the function like this

<div class="calc">
 <input type="text" id="txt1id<?= $row['id'] ?>" onkeyup="multiple(<?= $row['id'] ?>)">
 <input type="text" id="txt2id<?= $row['id'] ?>" onkeyup="multiple(<?= $row['id'] ?>)">
 <input type="text" id="resultid<?= $row['id'] ?>" title="Result shows here automatically">
</div>

And change in JS like below

<script>
 function multiple(rowid)
 { 
    var firstBox = parseInt(document.getElementById("txt1id"+rowid).value);
    var secondBox = parseInt(document.getElementById("txt2id"+rowid).value);
 }
</script>