首页 > 解决方案 > Using Jquery .each function in a PHP foreach loop

问题描述

I am quite new to jquery, and i couldn't use .each function in a php foreach function. I am trying to do a quantity, unit price, total price table. I don't know how many table rows does user need, therefore used foreach function. Here is an example what i am trying to do:

my deneme2.php file :

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width= <script type="text/javascript">
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script>deneme5.js</script>
</head>
<body>
<?php
$arr=[1,2];
foreach ($arr as $key=>$val){ ?>
<div>
    <input id="tst1"; type="text"; >
    <input id="tst2"; type="text"; >
    <input id="tst3"; type="text"; > <br><br>
  </div>
<?php } ?>
<input  id="asd"; type="submit"; value="hesapla">
</body>
</html>

And my deneme5.js file:

$(function(){
    $("#asd").click(function(){

        $("div").each(function(index){

            var a=$("#tst1").val();
            var b=$("#tst2").val();
            var c= parseInt(a)*parseInt(b);
            $("#tst3").val(c);

              });

    });


  });

Can you help me? what am i doing wrong?

标签: phpjqueryhtml

解决方案


您的代码中有许多语法错误。我稍微修改了一下。请把它和你的比较一下,看看你的错误在哪里。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
    <!-- here i have added your javascript code directly. You can include it like that: <script src="deneme5.js"></script>-->
    <script>
    $(function(){
      $("#asd").click(function()  {

        $(".row").each(function(index, element){
          var a = $(element).find(".tst1").val();
          var b = $(element).find(".tst2").val();
          var c = parseInt(a) * parseInt(b);
          $(element).find(".tst3").val(c);
        });

      });
    });
    </script>

</head>
<body>

<?php
$arr=[1,2];
foreach ($arr as $key=>$val){ ?>
<!-- in the following i have switched your ids into classes because ids have to be unique. Furthermore html attributes do not have to be separated by ';' -->
<div class="row">
    <input class="tst1" type="text">
    <input class="tst2" type="text">
    <input class="tst3" type="text"><br><br>
  </div>
<?php } ?>
<input id="asd" type="submit" value="hesapla">

</body>
</html>

这里所做的其中一件事是将 ID 的使用转换为类。ID 不能在页面上重复,因为这会导致 JavaScript 和 CSS 出现问题。


推荐阅读