简体   繁体   中英

Changing td's background color to success or danger

Here is my php where I want this td ( order_status ) change background color to green or success if the order was delivered and to change background color as danger or red if the order was canceled .

<?php
    if(!session_id()){
        session_start();
    }
    include_once '../fileadmin/dbinit.php';
    $todo = $_POST['todo'];
    $con = mysql_connect("localhost","root","","atec_coop");
    if (!$con){
        die("Can't connect".mysql_error());
    }
    mysql_select_db("atec_coop",$con);
    switch ($todo) {
        case "display":
            $sql = "SELECT * from tb_empgroc_master";
            $result = $atecCoop->query($sql);

            $html = ''; $ctr = 0;
            if ($result->num_rows){
                while ($row = $result->fetch_object()){
                $id = $row->empgrocmstID;
                $date_ordered = date("m-d-Y");
                $order_no = date($row->order_no);
                $total_items = number_format($row->total_items);
                $total_amount = number_format($row->total_amount,2);
                $order_status = wordwrap($row->order_status);

                $html .= "<tr id='$id'>";
                $html .= "<td class='date_ordered' style='text-align:center'>$date_ordered</td>";
                $html .= "<td class='order_no' style='text-align:center'>$order_no</td>";
                $html .= "<td class='total_items' style='text-align:right'>$total_items</td>";
                $html .= "<td class='total_amount' style='text-align:right'>$total_amount</td>";
                $html .= "<td class='order_status' style='text-align:center'>$order_status</td>";
                $html .= "</tr>";
                }
            }
            echo $html;
        break;
        case "Cancel":
            $Cancelquery = "UPDATE tb_empgroc_master SET order_status='Cancelled' WHERE empgrocmstID='".$_POST['empgrocmstID']."'";
            mysql_query($Cancelquery, $con);
        break;
        case "Approve":
            $Approvequery = "UPDATE tb_empgroc_master SET order_status='Delivered' WHERE empgrocmstID='".$_POST['empgrocmstID']."'";
            mysql_query($Approvequery, $con);
        break;
    }
?>

Here's my table form

<form class="form-horizontal" id="main-form" action="PHP_groceryReleasingProcess.php" method="POST">
    <table class="tablesorter table table-bordered table-condensed" id="cLoanOut" style="table-layout: fixed;">
        <colgroup>
            <col width="110">
            <col width="130">
            <col width="50">
            <col width="60">
            <col width="90">
        </colgroup>
        <thead>
            <tr>
                <th>Date Ordered</th>
                <th>Order No.</th>
                <th>Total Item(s)</th>
                <th>Total Amount</th>
                <th>Order Status</th>
            </tr>
        </thead>
        <tbody>
        </tbody>
    </table>
    <button id="Approve" role="button" class="btn btn-success" disabled>Approve Order</button>
    <button id="Cancel" role="button" class="btn btn-danger" disabled>Cancel Order</button>
</form>

And my javacript ajax call

$("#Approve").click(function(e) {
    e.preventDefault();
    var id = $('#cLoanOut tr.active').attr('id');
    bootbox.confirm("Are you sure you want to approve order?","No","Yes",function(r){
        if(r) {
            $.ajax({  
                url : "<?php echo $server_name; ?>/emcis_coopmain/process/PHP_groceryReleasingProcess.php",
                type : "POST",
                async : false,
                data : {
                    empgrocmstID:id,
                    todo:"Approve"
                },
                success:function(result){
                    bootbox.alert('Order Approved',function(){
                    $("#Approve").attr("disabled", true);
                    });
                    updateTable();
                }
            });   
        } else {

        }
    });
});
$("#Cancel").click(function(e) {
    e.preventDefault();
    var id = $('#cLoanOut tr.active').attr('id');
    bootbox.confirm("Are you sure you want to cancel order?","No","Yes",function(r){
        if(r) {
            $.ajax({
                url : "<?php echo $server_name; ?>/emcis_coopmain/process/PHP_groceryReleasingProcess.php",
                type : "POST",
                async : false,
                data : {
                    empgrocmstID:id,
                    todo:"Cancel"
                },
                success:function(result){
                    bootbox.alert("Order Cancelled",function(){
                    $("#Cancel").attr("disabled", true);
                    });
                    updateTable();
                }
            });   
        } else {

        }
    });
});

If i clicked Approve Order button , the data of order_status which is the td ( Pending ) will change to Delivered and if I clicked Cancel Order button it will change to Cancelled .

If success, I want to change the background color of that td into success/green if the order was approved/delivered . If canceled , change background color to danger/red .

I appreciate your help thanks.

It looks like this. Every tr has an active class when you click.

Date Ordered         Order No.     Total item(s) Total Amount   Order Status
 09-11-2015      15-09-0000000001        3          213.85        Pending
 09-11-2015      15-09-0000000002        1          130.00       Delivered
 09-11-2015      15-09-0000000003        2          134.07        Pending
 09-11-2015      15-09-0000000004        4          846.41       Cancelled

       <button>Approve Order</button> <button>Cancel Order</button>

My script for the updateTable();

function updateTable(){
//                $tbody = $('#cLoanOut tbody'),
//                url = $('#main-form').attr('action');
//                $.post("PHP_groceryReleasingProcess.php",{todo:"display"},function(response){
//                    $('.progress').hide();
//                    $tbody.html(response);
//                    $table.trigger('update');
//                },'html');
    var dataString = "todo=display";
    $.ajax({
        type: "POST",
        url: "<?php echo $server_name; ?>/emcis_coopmain/process/PHP_groceryReleasingProcess.php",
        data: dataString,
        success: function(sg){
            $("#cLoanOut tbody").empty();
            $("#cLoanOut").find('tbody').append(sg).trigger('update');
        },
        complete: function(){
            $('.progress').hide();
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            bootbox.alert('Search Failed.');
        }
    });
}

I added css to my form

.table-hover > tbody > tr > td.danger:hover {
     background-color: red !important;
}
.table-hover > tbody > tr > td.warning:hover {
     background-color: yellow !important;
}
.table-hover > tbody > tr > td.success:hover {
     background-color: green !important;
}

How can I call success for Delivered and danger for Cancelled if true to my td ( order_status )?

First you need to add a specific id to <td id="xxx"> of status order and then you can use same id in your jquery to add respective background color and change Text as "Delivered or Cancel".

You need to do this process on ajax call success event.

$("#xxx").css("background-color", "green");
$("#xxx").css("background-color", "red");

$("#xxx").html("Delivered");
$("#xxx").html("Cancel");

Something like this in your PHP loop :

$html .= '<tr id="$id" class="'. ($order_status == 'cancel' ? 'cancel' : 'approved') .'">';

You set a class to the TR depending on the $order_status. Then in your CSS :

tr.cancel td {
    background: red;
}
tr.approved td {
    background: green;
}

Instead of having two clicks and using same ajax you can simplify this:

$("#main-form button").click(function(e) {
    e.preventDefault();
    var $this = $(this); // cache the clicked button here
    var id = $('#cLoanOut tr.active').attr('id');
    bootbox.confirm("Are you sure you want to "+ this.id.toLowerCase() +" order?","No","Yes",function(r){
        if(r) {
            $.ajax({  
                url : "<?php echo $server_name; ?>/emcis_coopmain/process/PHP_groceryReleasingProcess.php",
                type : "POST",
                async : false,
                data : {
                    empgrocmstID:id,
                    todo:this.id // pass the button id here Approve/Cancel
                },
                success:function(result){
                    var msg = result === "Approved" ? "Order Approved" : "Order Cancelled";
                    bootbox.alert(msg, function(){
                       $this.prop("disabled", true); // use prop 
                    });
                    updateTable();
                },
                complete:function(){
                   $('#cLoanOut tr').each(function(){
                      $(this).find('td').last().addClass(function(){
                          if(this.textContent.trim() === "Cancelled"){
                              return "danger";
                          }else if(this.textContent.trim() === "Delivered"){ 
                              return "success";
                          }
                      });
                   });
                }
            });   
        } else {

        }
    });
});

In the above snippet what i have changed:

  1. Button selector within a context of your form. $("#main-form button") which lets you click on both buttons.
  2. var $this = $(this); you can use to have a variable which will later be used in the callbacks like error:fn, success:fn, complete:fn .
  3. this.id.toLowerCase() lets you have a dynamic popup message for both buttons.
  4. todo:this.id we are passing the clicked button's id.
  5. var msg = result === "Approved" ? "Order Approved" : "Order Cancelled"; this line can be used for both buttons messages if you return a specific text from the php.

  6. $this.prop("disabled", true); here $this is the clicked button as we cached it and use .prop() method to change any property like disabled, checked etc. .

  7. Add a complete callback to add a class to the tds. you can see that in the snippet.

In this answer 5 is where some issue might arise for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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