简体   繁体   English

如果表单元格等于100,则

[英]If table cell equals 100 then

I have the following table that uses Javascript to calculate the sum of cells. 我有下表使用Javascript计算单元格的总和。 When the inputs are entered Javascript the sums up the total of quantity and displays it in TD id="totalSum". 输入Javascript输入后,总和即为总数,并以TD id =“ totalSum”显示。

Ultimately I need to have it where when the totalSum equals 100, then execute php code. 最终我需要在totalSum等于100的地方使用它,然后执行php代码。

How do I get PHP to read the data in the totalSum and then execute PHP when it equals 100? 如何获取PHP以读取totalSum中的数据,然后在等于100时执行PHP?

HTML- HTML-

<table id="mytable" width="394">
    <colgroup>
        <col style="width: 50px;">
        <col>
        <col style="width: 60px;">
        <col style="width: 110px;">
    </colgroup>
    <tbody>
        <tr>
            <th  width="130" height="43"></th>
            <th width="52">Weight Select</th>
            <th width="181">New P</th>
        </tr>
        <tr>
            <td align="center" width="130">&nbsp;</td>
            <td align="center">
                <input type="text" size="2" value="1" id="qty_item_1" name="sum" >
            </td>
            <td align="center" id="total_item_1"></td>
        </tr>
        <tr>
             <td align="center" width="130"></td>
            <td align="center"  >
                <input type="text" size="2" value="1" id="qty_item_2" name="sum" >
            </td>
            <td align="center" id="total_item_2"></td>
        </tr>
        <tr class="tr">
            <td align="left" colspan="1"><strong>Grand Total:</strong></td>
            <td width="11" align="left" id="totalSum"></td>
        </tr>
    </tbody>
</table>

Javascript- Javascript-

<script type="text/javascript">
    var bIsFirebugReady = (!!window.console && !!window.console.log);
    $(document).ready(function (){
        // update the plug-in version
        $("#idPluginVersion").text($.Calculation.version);

                                /*
                                $.Calculation.setDefaults({
                                onParseError: function(){
                                this.css("backgroundColor", "#cc0000")
                                }
                                , onParseClear: function (){
                                this.css("backgroundColor", "");
                                }
                                });
                                */
        // bind the recalc function to the quantity fields
        $("input[id^=qty_item_]").bind("keyup", recalc);

        // run the calculation function now
        recalc();

        // automatically update the "#totalSum" field every time
        // the values are changes via the keyup event
        $("input[name^=sum]").sum("keyup", "#totalSum");

        // automatically update the "#totalAvg" field every time
        // the values are changes via the keyup event
        $("input[name^=avg]").avg({
            bind:"keyup"
            , selector: "#totalAvg"
                // if an invalid character is found, change the background color
            , onParseError: function(){
                this.css("backgroundColor", "#cc0000")
            }
            // if the error has been cleared, reset the bgcolor
            , onParseClear: function (){
                this.css("backgroundColor", "");
            }
        });

        // automatically update the "#minNumber" field every time
        // the values are changes via the keyup event
        $("input[name^=min]").min("keyup", "#numberMin");

        // automatically update the "#minNumber" field every time
        // the values are changes via the keyup event
        $("input[name^=max]").max("keyup", {
            selector: "#numberMax"
            , oncalc: function (value, options){
                // you can use this to format the value
                $(options.selector).val(value);
            }
        });

        // this calculates the sum for some text nodes
        $("#idTotalTextSum").click(function() {
            // get the sum of the elements
            var sum = $(".textSum").sum();

            // update the total
            $("#totalTextSum").text("$" + sum.toString());
        });

        // this calculates the average for some text nodes
        $("#idTotalTextAvg").click(function() {
            // get the average of the elements
            var avg = $(".textAvg").avg();

            // update the total
            $("#totalTextAvg").text(avg.toString());
        });

    });

    function recalc(){
        $("[id^=total_item]").calc(
            // the equation to use for the calculation
            "qty * price / 100",
            // define the variables used in the equation, these can be a jQuery object
        {
            qty: $("input[id^=qty_item_]"),
            price: $("[id^=price_item_]")
        },

        // define the formatting callback, the results of the calculation are passed to this function
        function (s){
            // return the number as a dollar amount
            return "" + s.toFixed(2);
        },
            // define the finish callback, this runs after the calculation has been complete
            function ($this){
                // sum the total of the $("[id^=total_item]") selector
                var sum = $this.sum();
                $("#grandTotal").text(
                    // round the results to 2 digits
                    "" + sum.toFixed(2)
                );  
            }
        );
    }
</script>

Your question does not show how you trigger summing up the values, or checking the value of cell id="totalSum" , so in my solution I added a button id="mybutt" to do that. 您的问题没有显示如何触发对这些值求和,或检查单元格id="totalSum" ,因此在我的解决方案中,我添加了一个按钮id="mybutt"来完成此操作。

Working jsFiddle here 在这里工作jsFiddle

All you need to know is in the above jsFiddle, and in the section below discussing the some_php_file.php . 您只需要在上面的jsFiddle中以及在下面讨论some_php_file.php的部分中就知道了。 What follows now is a description of how the code works, if you need that. 如果需要的话,下面是对代码工作方式的描述。


  1. First, we get the collection of all table cells where the id starts with qty_item : 首先,我们获取idqty_item开头的所有表单元的集合:

    $('[id^=qty_item_]')

  2. Next, we iterate through this collection using the .each method: 接下来,我们使用.each方法遍历此集合:

    var ttl = 0;
    $('[id^=qty_item_]').each(function() {
    str = $(this).val();
    ttl += Number(str);
    });

  3. Then, inject the total into the cell with id="totalSum" 然后,将总计注入到具有id="totalSum"的单元格中

    $('#totalSum').text(ttl).trigger('change');

Note that we trigger a change event on that same element (table cell). 请注意,我们在同一元素(表单元)上触发了一个change事件。 That immediately fires this code: 立即触发此代码:

$('#totalSum').change(function() {
    var sum = $(this).text();
    alert('Value: ' + sum);
    if (Number(sum) > 99) {
        alert('Value > 100. AJAX will begin, but cannot finish because jsFiddle cannot do ajax. Just look at syntax.').
        $.ajax({
            type: "POST",
            url: "some_php_file.php",
            data: 'myTotalSum='+sum,
            success:function(somedata){
                alert(somedata);
            }
        });
    }
});

In the AJAX code block, notice the URL that is specified. 在AJAX代码块中,注意指定的URL。 A PHP file with the same name must exist on the server (in same folder as your HTML code, for this example). 服务器上必须存在一个具有相同名称的PHP文件(对于本示例,该文件与HTML代码位于同一文件夹中)。 It will receive the info sent via AJAX in a POST variable called myTotalSum . 它将在名为myTotalSum的POST变量中接收通过AJAX发送的信息。

Once you have that number, your PHP file can stick it into the database. 一旦有了该编号,您的PHP文件便可以将其粘贴到数据库中。 If you want, you can even have the PHP file send information back to the webpage (it arrives in the success function of the AJAX code block). 如果需要,您甚至可以让PHP文件将信息发送回网页(它到达AJAX代码块的success功能中)。 Note that the javascript on the webpage continues processing without waiting for the PHP page to finish. 请注意,网页上的javascript 无需等待 PHP页面完成即可继续处理 If you need the javascript to wait, then you would insert async: false, somewhere near the top of that code block. 如果您需要JavaScript来等待,则可以在该代码块顶部附近的位置插入async: false,

To see this actually work, create a text file with this name and these contents: 要查看此方法的实际效果,请创建一个具有此名称和以下内容的文本文件:

some_php_file.php some_php_file.php

<?php
    $theSum = $_POST['myTotalSum'];
    $r = '<h2>Mr. PHP received this number:</h2><h1>' .$theSum. '</h1>';
    echo $r;

The echo in the PHP file sends the contents of variable $r back to the AJAX code block, where it is received in the success function. echo在PHP文件发送变量的内容$r回AJAX代码块,它在接收到success功能。 Important: this incoming data must be dealt with here, and no where else. 重要:此传入数据必须在此处处理,而在其他地方则不能处理。 It will not exist outside the success function. 成功函数之外将不存在它。

To access received data outside the success function, stick the received data into an element, such as a hidden input element, like this: 要在成功函数之外访问接收到的数据,请将接收到的数据粘贴到一个元素中,例如隐藏的input元素,如下所示:

success:function(mydata){
    $('#a_hidden_input_element').val(mydata);
}

Here is an SO post with some additional AJAX code examples. 这是SO帖子 ,其中包含一些其他AJAX代码示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM