dimanche 18 décembre 2016

Dynamically generated checkboxes not included in form during $.post()

Question

My form is generated dynamically from content fetched form a database using:

$("#category_selector").change(function(event) {
    $("#listDB").css('display', 'none');
    $("#listDB").find(".catHead").remove();
    $("#listDB").find(".data").remove();

    $("#action").val('getList');
    var data = $("#list :input").serialize();
    alert(data);
    $.post($("#list").attr('action'), data, function(json)
    {
        if(json.listArr.length>0)
        {
            $.each(json.listArr, function() {
                var $tr = $('<tr>', {
                    class   : "catHead",
                });
                var $td = $('<td>', {
                    colspan : 11,
                    text    : this.category
                });
                $("#listDB").append($tr.append($td));

                $.each(this.value, function() {
                    var $tr = $('<tr>',{
                        class : "data"
                    });

                    var $td = $('<td>', {
                        html    : '<input type="checkbox" id="selected" value="'+this.id+'" name="selected" /></td>'
                    });$tr.append($td);
                    $td = $('<td>', {
                        text    : this.id
                    });$tr.append($td);
                    $td = $('<td>', {
                        text    : this.catCount
                    });$tr.append($td);
                    $td = $('<td>', {
                        text    : this.shop
                    });$tr.append($td);
                    $td = $('<td>', {
                        text    : this.item
                    });$tr.append($td);
                    $td = $('<td>', {
                        text    : this.qnty
                    });$tr.append($td);
                    $td = $('<td>', {
                        text    : this.unit
                    });$tr.append($td);
                    $td = $('<td>', {
                        text    : this.price_based_on
                    });$tr.append($td);
                    $td = $('<td>', {
                        text    : this.mrp
                    });$tr.append($td);
                    $td = $('<td>', {
                        text    : this.sellers_price
                    });$tr.append($td);

                    var formattedDate = new Date(this.last_updated_on);
                    var d = formattedDate.getDate();
                    var m =  formattedDate.getMonth();
                    m += 1;  // JavaScript months are 0-11
                    var y = formattedDate.getFullYear();
                    var date = (d<10?"0":"")+d+"-"+(m<10?"0":"")+m+"-"+y;
                    $td = $('<td>', {
                        text    : date
                    });$tr.append($td);

                    $("#listDB").append($tr);
                });
            });
        }
    },"json");
    $("#listDB").fadeIn(500);
}); 

Of note in this entire section is the following lines used to generate checkboxes :

var $td = $('<td>', {
    html    : '<input type="checkbox" id="selected" value="'+this.id+'" name="selected" /></td>'
});$tr.append($td);

I used an alert on the data processed by serialize() to check if my data contains the selected checkboxes, but they don't. The code I used to do so was :

var data = $("#list :input").serialize();
alert(data);

The output was:

category_selector=All&action=getList

So, my problem is that no matter how many checkboxes I click, they don't get sent for processing as they're dynamically generated. How do I fix this? Is something else causing my problem, if not this? How do we fix it?


Code dump

For the sake of entirity, here's my entire code:

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>SomuFinance - Personal Finance Manager</title>
    <link rel="stylesheet" type="text/css" href="indexStyle.css">
    <script src="scripts/jquery-3.1.0.min.js"></script>
    <script type="text/javascript" src="scripts/jquery.validate.min.js"></script>
    <script type="text/javascript" src="viewDB.js"></script>
    <style type="text/css">
        #addItemContainer {
            background-color: rgba(204,207,232,1);
        }
    </style>
    <script type="text/javascript">
        var flag=0;
    </script>
</head>
<body>
    <form id="list" method="post" action="viewData.php">
        <div id="container">
            <h1>View Database</h1>
            <select name="category_selector" id="category_selector">
                <option value="All" selected>All</option>
            </select>
            <input type="button" class="button" name="edit" id="edit" value="Edit" />
            <input type="button" class="button" name="delete" value="Delete" />
            <input type="hidden" id="action" name="action">
            <table id="listDB">
                <tr>
                    <th>Select</th>
                    <th>ID</th>
                    <th>Category ID</th>
                    <th>Shop</th>
                    <th>Item</th>
                    <th>Quantity</th>
                    <th>Unit</th>
                    <th>Price Based On</th>
                    <th>MRP</th>
                    <th>Seller's Price</th>
                    <th>Last Updated On</th>
                </tr>
            </table>
        </div>
    </form>

    <div class="dialogBG">
        <div id="deleteConfirmDialog" class="dialog">
            <div class="closeDialog"></div>
            <p>Sure you want to delete the selected Data?</p>
            <input type="button" id="confirmDelete" class="dialogButton" name="confirmDelete" value="Delete" />
            <input type="button" id="cancelDelete" class="dialogButton cancelButton" name="cancelDelete" value="Cancel" />
        </div>
    </div>

    <div class="dialogBG">
        <div id="addItemContainer" class="dialog">
            <div class="closeDialog"></div>
            <h1>Edit Item</h1>
            <form id="data" method="post" action="<?php $_SERVER['PHP_SELF']; ?>">

                <div class="leftAligned">
                    <input type="hidden" id="id" name="id" value="<?php echo $id; ?>" required>
                    <div class="inp">
                        <label for="shop">ID : </label>
                        <input type="text" id="id_disp" name="id_disp" value="<?php echo $id; ?>" required disabled>
                    </div> <br>
                    <div class="inp">
                        <label for="shop">Shop : </label>
                        <input type="text" id="shop" name="shop" value="<?php echo $shop; ?>" required>
                    </div> <br>
                    <div class="inp">
                        <label for="category">Category : </label>
                        <input type="text" id="category" name="category" value="<?php echo $category; ?>" required>
                    </div> <br>
                    <div class="inp">
                        <label for="item">Item : </label>
                        <input type="text" id="item" name="item" value="<?php echo $item; ?>" required>
                    </div> <br>
                    <div class="inp">
                        <label for="qnty">Quantity : </label>
                        <input type="text" id="qnty" name="qnty" value="<?php echo $qnty; ?>" required>
                    </div> <br>
                    <div class="inp">
                        <label for="unit">Unit : </label>
                        <input type="text" id="unit" name="unit" value="<?php echo $unit; ?>" required>
                    </div> <br>
                    <div class="inp">
                        <label for="price_based_on">Price based on : </label>
                        <select name="price_based_on" id="price_based_on">
                            <option value="kilos" <?php if($price_based_on=='Kilos') echo "selected" ?> >Kilos</option>
                            <option value="packet" <?php if($price_based_on=='Packet') echo "selected" ?> >Packet</option>
                            <option value="bottle" <?php if($price_based_on=='Bottle') echo "selected" ?> >Bottle</option>
                            <option value="box" <?php if($price_based_on=='Box') echo "selected" ?> >Box</option>
                            <option value="piece" <?php if($price_based_on=='Piece') echo "selected" ?> >Piece</option>
                        </select>
                    </div> <br>
                    <div class="inp">
                        <label for="mrp">MRP (₹) : </label>
                        <input type="text" id="mrp" name="mrp" value="<?php echo $mrp; ?>" required>
                    </div> <br>
                    <div class="inp">
                        <label for="sellers_price">Seller's Price (₹) : </label>
                        <input type="text" id="sellers_price" value="<?php echo $sellers_price; ?>" name="sellers_price" required>
                    </div> <br>
                    <div class="inp">
                        <label for="last_updated_on">Last Updated on : </label>
                        <input type="date" id="last_updated_on" name="last_updated_on" value="<?php echo $last_updated_on; ?>" required>
                    </div>
                </div>
                <div class="inp">
                    <input id="insertButton" type="submit" name="submit" value="Update">
                </div>
                <div id="message">

                    <script>
                    $(document).ready(function(){

                        $( "#data" ).validate({
                          rules: {
                            qnty: {
                              number: true
                            },
                            mrp: {
                              number: true
                            },
                            sellers_price: {
                              number: true
                            }
                          },
                          messages: {
                            qnty : {
                                number: '<br> <span class="failure err">Enter a valid quantity</span>'
                            },
                            mrp : {
                                number: '<br> <span class="failure err">Enter a valid MRP</span>'
                            },
                            sellers_price : {
                                number: '<br> <span class="failure err">Enter a valid Price</span>'
                            },
                          }
                        });
                    });
                    </script>
                </div>
            </form>
        </div>
    </div>
    <script type="text/javascript">

        $(document).ready(function(){


            if(flag===1)
            {
                $("#addItemContainer").show(200).parent(".dialogBG").fadeIn(200);
            }

            $("#edit").click(function(event) {
                $("#category_selector").val("All");
            });
        });
    </script>

    <?php
        mysqli_close($dbc);
    ?>
</body>
</html>

PHP :

<?php
    ini_set('display_errors', '1');
    error_reporting(E_ALL);

    ob_start();


    if(!empty($_GET)&&$_GET['action']=='getCat') // Provides list of Categories as JSON
    {
        $query1 = "SELECT DISTINCT category FROM grocery";
        $result1 = dbQuery($query1);

        $catArr=array();
        while($row = mysqli_fetch_array($result1))
            array_push($catArr, array('category' => $row['category']));

        echo json_encode(array('catArr' => $catArr));
        exit;
    }

    if(!empty($_POST)&&($_POST['action']=='confirmDelete')) // Deletes an item from the DB
    {
        foreach ($_POST['selected'] as $delete_id) 
        {
            $query = "DELETE FROM grocery WHERE id = $delete_id";
            dbQuery($query);
        }
    }

    if(!empty($_POST)&&$_POST['action']=='getList') // Provides entire DB of a selected category or all categories based on category_selector
    {
        $listArr=array();
        if($_POST['category_selector']!='All')
        {
            $category = $_POST['category_selector'];
            $query = "SELECT * FROM grocery WHERE category='$category' ORDER BY item ASC";
            $result = dbQuery($query);

            $rowArr=array();
            $catCount=1;
            while($inRow = mysqli_fetch_array($result))
            {
                $id = $inRow['id'];
                $shop = $inRow['shop'];
                $item = $inRow['item'];
                $qnty = $inRow['quantity'];
                $unit = $inRow['unit'];
                $price_based_on = $inRow['price_based_on'];
                $mrp = $inRow['MRP'];
                $sellers_price = $inRow['sellers_price'];
                $last_updated_on = $inRow['last_updated_on'];

                array_push($rowArr, array('id' => $id, 'catCount' => "$catCount", 'shop' => $shop, 'item' => $item, 'qnty' => $qnty, 'unit' => $unit, 'price_based_on' => $price_based_on, 'mrp' => $mrp, 'sellers_price' => $sellers_price, 'last_updated_on' => $last_updated_on));

                $catCount++;
            }

            array_push($listArr, array('category' => $category, 'value' => $rowArr));
            echo json_encode(array('listArr' => $listArr));
            exit;
        }
        else
        {
            $query1 = "SELECT DISTINCT category FROM grocery";
            $result1 = dbQuery($query1);

            while($row = mysqli_fetch_array($result1))
            {
                $category = $row['category'];
                $query2 = "SELECT * FROM grocery WHERE category='$category' ORDER BY item ASC";
                $result2 = dbQuery($query2);

                $rowArr=array();
                $catCount=1;
                while($inRow = mysqli_fetch_array($result2))
                {
                    $id = $inRow['id'];
                    $shop = $inRow['shop'];
                    $item = $inRow['item'];
                    $qnty = $inRow['quantity'];
                    $unit = $inRow['unit'];
                    $price_based_on = $inRow['price_based_on'];
                    $mrp = $inRow['MRP'];
                    $sellers_price = $inRow['sellers_price'];
                    $last_updated_on = $inRow['last_updated_on'];

                    array_push($rowArr, array('id' => $id, 'catCount' => "$catCount", 'shop' => $shop, 'item' => $item, 'qnty' => $qnty, 'unit' => $unit, 'price_based_on' => $price_based_on, 'mrp' => $mrp, 'sellers_price' => $sellers_price, 'last_updated_on' => $last_updated_on));

                    $catCount++;
                }
                array_push($listArr, array('category' => $category, 'value' => $rowArr));
            }
            echo json_encode(array('listArr' => $listArr));
            exit;
        }
    }

    function dbQuery($query)
    {
        $dbc =  mysqli_connect('localhost','root','atlantis2016','itemDB')
                    or die("Error Connecting to Database");
        $result = mysqli_query($dbc,$query)
                    or die("Error Querying Database");
        return $result;
    }
    function fail($message) 
    {
        die(json_encode(array('status' => 'fail', 'message' => $message)));
    }
    function success($message) 
    {
        die(json_encode(array('status' => 'success', 'message' => $message)));
    }
?>

jQuery :

$(document).ready(function() {

    /*  Code to Generate the categories in the dropdown list Begins ----------------------------------------------------------------------------------------------------------------------------------------------------*/
    var catArr=[];
    $.get("viewData.php?action=getCat", function(json) {
        if(json.catArr.length>0)
            $.each(json.catArr, function() 
            {
                catArr.push(this.category);
            });

        $.each(catArr, function(index, el) {
            $("#category_selector").append($('<option>', { 
                value: el,
                text : el
            }));
        });

        $("#category_selector").trigger('change');

    }, 'json');
    /*  Code to Generate the categories in the dropdown list Ends ----------------------------------------------------------------------------------------------------------------------------------------------------*/

    /*  Code to SWITCH BETWEEN BUTTON CLICKS Begins ------------------------------------------------------------------------------------------------------------------------------------------------------------------*/
    $('.button').click(function(event){
        var checked = $("#list input:checked").length > 0;
        if($(this).val()=="Delete"&&checked) //To confirm Delete
        {
            $("#deleteConfirmDialog").show(200).parent(".dialogBG").fadeIn(200);
            $("#action").val('confirmDelete');
        }
        else if($(this).val()=="Edit"&&checked)
        {
            $("#action").val('edit');
        }
    });
    /*  Code to SWITCH BETWEEN BUTTON CLICKS Ends --------------------------------------------------------------------------------------------------------------------------------------------------------------------*/

    /*  Code to DISPLAY ITEMS IN THE DATABASE Begins -----------------------------------------------------------------------------------------------------------------------------------------------------------------*/
    $("#category_selector").change(function(event) {
        $("#listDB").css('display', 'none');
        $("#listDB").find(".catHead").remove();
        $("#listDB").find(".data").remove();

        $("#action").val('getList');
        var data = $("#list :input").serialize();
        alert(data);
        $.post($("#list").attr('action'), data, function(json)
        {
            if(json.listArr.length>0)
            {
                $.each(json.listArr, function() {
                    var $tr = $('<tr>', {
                        class   : "catHead",
                    });
                    var $td = $('<td>', {
                        colspan : 11,
                        text    : this.category
                    });
                    $("#listDB").append($tr.append($td));

                    $.each(this.value, function() {
                        var $tr = $('<tr>',{
                            class : "data"
                        });

                        var $td = $('<td>', {
                            html    : '<input type="checkbox" id="selected" value="'+this.id+'" name="selected" /></td>'
                        });$tr.append($td);
                        $td = $('<td>', {
                            text    : this.id
                        });$tr.append($td);
                        $td = $('<td>', {
                            text    : this.catCount
                        });$tr.append($td);
                        $td = $('<td>', {
                            text    : this.shop
                        });$tr.append($td);
                        $td = $('<td>', {
                            text    : this.item
                        });$tr.append($td);
                        $td = $('<td>', {
                            text    : this.qnty
                        });$tr.append($td);
                        $td = $('<td>', {
                            text    : this.unit
                        });$tr.append($td);
                        $td = $('<td>', {
                            text    : this.price_based_on
                        });$tr.append($td);
                        $td = $('<td>', {
                            text    : this.mrp
                        });$tr.append($td);
                        $td = $('<td>', {
                            text    : this.sellers_price
                        });$tr.append($td);

                        var formattedDate = new Date(this.last_updated_on);
                        var d = formattedDate.getDate();
                        var m =  formattedDate.getMonth();
                        m += 1;  // JavaScript months are 0-11
                        var y = formattedDate.getFullYear();
                        var date = (d<10?"0":"")+d+"-"+(m<10?"0":"")+m+"-"+y;
                        $td = $('<td>', {
                            text    : date
                        });$tr.append($td);

                        $("#listDB").append($tr);
                    });
                });
            }
        },"json");
        $("#listDB").fadeIn(500);
    }); 
    /*  Code to display items in the database Ends -------------------------------------------------------------------------------------------------------------------------------------------------------------------*/

    /*  Code to CONFIRM DELETE Begins --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------*/
    $('#confirmDelete').click(function(){


        $(".closeDialog").trigger("click");
    });
    /*  Code to CONFIRM DELETE Ends ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------*/

    /*  Code to CONTROL BUTTON AND DIALOG BEHAVIOUR Begins -----------------------------------------------------------------------------------------------------------------------------------------------------------*/
    $('#cancelDelete').click(function(){
        $("input:checkbox[name='selected']").prop('checked', false);
    });
    $(".closeDialog").click(function (e){
        $(this).parent(".dialog").hide('200').parent(".dialogBG").fadeOut('200');
    });
    $(".cancelButton").click(function (e){
        $(this).parent(".dialog").hide('200').parent(".dialogBG").fadeOut('200');
    });
    /*  Code to CONTROL BUTTON AND DIALOG BEHAVIOUR Ends -------------------------------------------------------------------------------------------------------------------------------------------------------------*/

});

Thank you for your time.




Aucun commentaire:

Enregistrer un commentaire