从php循环获取值并在keyup上获取多个值

时间:2016-10-22 09:02:24

标签: javascript php foreach

我有一个动态创建的PHP循环,有两个文本框和一个结果列。

我需要的是,只需输入前两个框的值,并在结果框附近显示结果。

PHP循环

<?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.

脚本是

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

1 个答案:

答案 0 :(得分:1)

将行ID传递给像这样的函数

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

如下所示改变JS

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