duanmeng3126 2016-04-08 16:36
浏览 69

在从数据库获取信息的循环中将变量通过php传递到javascript

Within this section of code I am using PHP to pull information from a mysql database. Its in a loop so that all of the rows in the database will be presented on the page. There is a price in each row, and I total those (in the loop) up and display them as one total. I want to add functionality that allows for a checkbox that needs to be checked in order for the price to be added to the total, but I cant figure out where and with what technology I should be using to do this.

Here is the snippet of code:

$sql = "SELECT CourseNum, CourseName, CreditNum, InstructorName, BookName, NewPrice, UsedPrice, Section_Name, BookLink FROM BookInfo";    //       echo"<a href='$row["BookLink"].'>$row["BookName"].</a>";
$test = "test";
$result = $conn->query($sql);

echo"<h2>CIT Course requirements <hr></h2>";
echo"<h2><small>Math & Science</small></h2>";
if ($result->num_rows > 0) {
     echo "$tableHeaderInfo";
     // output data of each row
     while($row = $result->fetch_assoc()) {
         if($row["Section_Name"] == mth_sci){    

                echo "<tr><td class='col-xs-.3'><input type='checkbox' ID='checbox123' name='checkbox123' value='1' onClick='apply(this);'  /> </td><td class='col-xs-1'>" . $row["CourseNum"]. "</td><td class='col-xs-3'>" . $row["CourseName"]. " </td><td class='col-xs-2'>" . $row["InstructorName"]." </td><td><a href='" . $row["BookLink"] . "'>" . $row["BookName"] . "</a></td><td class='col-xs-1'>$" . money_format('%(#10n', $row["NewPrice"]). " </td><td class='col-xs-1'>$" . money_format('%(#10n', $row["UsedPrice"]). " </td></tr>";

                $test = "test";

                 echo "

                        <script>

                        apply = function (obj)
                        {
                            if(obj.checked){  
                                obj.parentNode.parentNode.style.backgroundColor='lightgreen'


                            }
                            else
                            obj.parentNode.parentNode.style.backgroundColor=''
                        }
                        </script>                    

                 ";

                $sum_total1 += $row["NewPrice"];  //This totals the prices right now
                $sum_total2 += $row["UsedPrice"];



         }
     }
     echo "</table>";
} else {
     echo "0 results";
}

So instead of $sum_total2 += $row["UsedPrice"]; being used to total the price, there will be a similar line within the echo'd javascript function named 'apply'.

Does this seem like an okay way to total the numbers? How do I get that addition to happen from within the loop so I can pull the price variables?

Thanks for the help :) I can post the full page of code if needed.

Edit:

I my main goal is to use to total up the prices while within the loop, but only if the checkbox is checked.

for example

                            if(obj.checked){  
                            obj.parentNode.parentNode.style.backgroundColor='lightgreen'

                            //does the total here ie total += $NewPrice
                        }

But can cant work it like this since the loop has already finished by time the checkbutton event happens..

edit 3:

The snippet of code is basically displaying the image below (minus some bootstrap)

Example image

http://pastie.org/10790551 (link to the code from image above)

When the checkbox is pressed, the total will be updated. It seems like my technique wont work for this since I need to catch the bookprice variables while inside of the loop?

  • 写回答

1条回答 默认 最新

  • douyuliu9527 2016-04-08 16:50
    关注

    I'm not entirely sure I understand what you're going for, but why not let javascript do the summing up, if you handle the checkbox click with javascript anyway? You could include the price of the row within the checkbox element. Either as a tag or as a variable passed to apply...

    Then you add/subtract it from the sum (I'm guessing this is always in a certain element). Or you could let the javascript loop through all the checkbox-elements to fetch the price from a tag if checked and display the sum.


    Answer to update:

    Okay, so your checkboxes look like this:

    <input type='checkbox' ID='checbox123' name='checkbox123' value='1' onClick='apply(this);'  /> 
    

    First of all, you shouldn't use the same id for more than one element. If you need to give it an ID it should rather be 'checkbox' + [some unique ID]. If it's for CSS, use class. The name on the other hand, you can take advantage of if it's the same for all of them (and assuming you're not using HTML5), because that allows you to do this:

    var checkboxes = document.getElementsByName("checkbox123");
    

    checkboxes is now a collection of all your checkboxes named checkbox123, and you can iterate through them :)


    Answer to new update:

    One way of solving this, is that you make sure to put your totals into html elements with ID tags. Then make sure to give your checkboxes the price information like this: (btw, I removed the ID-tag, as you really, really shouldn't reuse the same ID for several elements. And what are you using value for??)

    <input type='checkbox' style='width:40px; height:40px;' name='checkbox123' value='1' price1='" . [insert new price here] . "' price2=' . [insert used price here] . ' onClick='apply(this);'  /> 
    

    And then your apply-function could look something like this: (also, don't forget semicolons in javascript!)

    apply = function (obj)
    {
        if(obj.checked){  
            obj.parentNode.parentNode.style.backgroundColor='#99ff99';
        }
        else {
            obj.parentNode.parentNode.style.backgroundColor=''; //what is this for??
        }
    
        var checkboxes = document.getElementsByName("checkbox123");
        var price1sum = 0;
        var price2sum = 0;
        for (var i=0; i<checkboxes.length; i++) {
            if (checkboxes[i].checked) {
                price1sum += checkboxes[i].getAttribute("price1");
                price2sum += checkboxes[i].getAttribute("price2");
            }
        }
        /*
        display price1sum and price2sum in html elements using something like this:
        document.getElementById("ID for total of new price").innerText = price1sum;
        */
    }
    

    Obviously doing a loop for every single checkbox-click is not the most effecient solution, but given your current structure, I think it's the easiest, and if you don't have a lot of rows, I don't think you'll notice anything.

    评论

报告相同问题?

悬赏问题

  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)