【问题标题】:If table cell equals 100 then如果表格单元格等于 100,则
【发布时间】:2018-07-05 04:52:33
【问题描述】:

我有下表,它使用 Javascript 来计算单元格的总和。当输入 Javascript 时,总数量相加并显示在 TD id="totalSum" 中。

最终我需要在totalSum等于100的时候得到它,然后执行php代码。

如何让 PHP 读取 totalSum 中的数据,然后在等于 100 时执行 PHP?

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-

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

【问题讨论】:

  • 请尽量简化您的问题。这是您在此处发布的大量代码。还有Don't Use Tables for Layout
  • 要么将数据放入表单并提交表单,要么使用 AJAX 将值发送到 PHP。
  • 当#totalSum达到100时,必须使用AJAX发送数据到服务器供PHP使用

标签: javascript php html-table


【解决方案1】:

您的问题没有显示您如何触发对值求和或检查单元格 id="totalSum" 的值,因此在我的解决方案中,我添加了一个按钮 id="mybutt" 来执行此操作。

Working jsFiddle here

所有你需要知道的是上面的 jsFiddle,以及下面讨论 some_php_file.php 的部分。下面是对代码如何工作的描述,如果您需要的话。


  1. 首先,我们得到idqty_item开头的所有表格单元格的集合:

    $('[id^=qty_item_]')

  2. 接下来,我们使用.each 方法遍历这个集合:

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

  3. 然后,用id="totalSum"将总数注入单元格

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

请注意,我们在同一元素(表格单元格)上触发了change 事件。立即触发此代码:

$('#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);
            }
        });
    }
});

在 AJAX 代码块中,注意指定的 URL。服务器上必须存在同名的 PHP 文件(在本示例中,与您的 HTML 代码位于同一文件夹中)。它将在名为 myTotalSum 的 POST 变量中接收通过 AJAX 发送的信息。

一旦你有了这个数字,你的 PHP 文件就可以把它存入数据库。如果需要,您甚至可以让 PHP 文件将信息发送回网页(它到达 AJAX 代码块的 success 函数)。请注意,网页上的 javascript会继续处理,而无需等待 PHP 页面完成。如果您需要 javascript 等待,那么您可以在该代码块顶部附近的某处插入 async: false,

要查看它的实际效果,请创建一个具有此名称和以下内容的文本文件:

some_php_file.php

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

PHP 文件中的echo 将变量$r 的内容发送回AJAX 代码块,在success 函数中接收它。 重要提示:这些传入的数据必须在此处处理,而不能在其他地方处理。它不会存在于success函数之外。

要在成功函数之外访问接收到的数据,请将接收到的数据粘贴到一个元素中,例如隐藏的input 元素,如下所示:

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

Here is an SO post 以及一些额外的 AJAX 代码示例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-27
    • 2017-10-11
    • 2015-02-05
    • 1970-01-01
    相关资源
    最近更新 更多