locked
Can not able to add row data in Jquery list variable? RRS feed

  • Question

  • User-199788946 posted

    I have following html table I have add button when i press add button table row add dynamically by using JQuery see image link below:

    https://drive.google.com/file/d/1PxbpX4icWpPHg_jKbsoUC2RolHvgzNOZ/view?usp=sharing

    <table id="submissionTable" class="table table-bordered">
                                <thead>
                                    <tr>
                                        <td>Debit Account</td>
                                        <td>Amount</td>
                                        <td>Expense Description</td>
                                    </tr>
                                </thead>
    
                                <tr class="mycontainer" id="tablerow0">
                                    <td>
                                        <div class="editor-field">
                                            <select id="productCategory" class="productCategory pc form-control">
                                                <option>Select</option>
                                            </select>
                                            <span class="error">Select Category</span>
                                        </div>
                                    </td>
                                    <td>
                                        <div class="editor-field">
                                            <input class="rate text-box single-line" id="rate" type="text" value="" />
                                            <span class="error">Valid amount required</span>
                                        </div>
                                    </td>
                                    <td>
                                        <div class="editor-field">
                                            <input class="description text-box single-line" id="description" type="text" value="" />
                                        </div>
                                    </td>
                                    <td>
                                        <input type="button" id="add" value="add" style="width:80px" class="btn btn-success" />
                                    </td>
                                    <td>
                                    </td>
                                </tr>
    
                            </table>
    

    also two div one for appending row other for button.

                <div id="orderItems">
                                <table class="table table-responsive" id="orderdetailsItems"></table>
                                <span id="orderItemError" style="color:red"></span>
                            </div>
                            <div style="padding:10px 0; text-align:right">
                                <input id="submit" type="button" value="Save" class="btn btn-warning" style="padding:10px 20px" />
                            </div>

    I have load select option data from database like and it works fine

        var Categories = []
        //fetch categories from database
        function LoadCategory(element) {
            if (Categories.length == 0) {
                //ajax function for fetch data
                $.ajax({
                    type: "GET",
                    url: '/ExpenditureReq/GetAccountHeadDesc',
                    success: function (data) {
                        Categories = data;
                        //render catagory
                        renderCategory(element);
                    }
                })
            }
            else {
                //render catagory to the element
                renderCategory(element);
            }
        }
        function renderCategory(element) {
            debugger;
            var $ele = $(element);
            $ele.empty();
            $ele.append($('<option/>').val('0').text('Select'));
            $.each(Categories, function (i, val) {
                $ele.append($('<option/>').val(val.DebitAcHead).text(val.Description));
            })
        }

    I have used some jquery validation but no problem in that :

        $(document).ready(function () {
            //Add button click event
            $('#add').click(function () {
                //validation and add order items
                var isAllValid = true;
                if ($('#productCategory').val() == "0") {
                    isAllValid = false;
                    $('#productCategory').siblings('span.error').css('visibility', 'visible');
                }
                else {
                    $('#productCategory').siblings('span.error').css('visibility', 'hidden');
                }
    
                if (!($('#description').val() != '')) {
                    isAllValid = false;
                    $('#description').siblings('span.error').css('visibility', 'visible');
                }
                else {
                    $('#description').siblings('span.error').css('visibility', 'hidden');
                }
    
                if (!($('#rate').val().trim() != '' && !isNaN($('#rate').val().trim()))) {
                    isAllValid = false;
                    $('#rate').siblings('span.error').css('visibility', 'visible');
                }
                else {
                    $('#rate').siblings('span.error').css('visibility', 'hidden');
                }
    
                if (isAllValid) {
                    var $newRow = $('#tablerow0').clone().removeAttr('id');
                    $('.pc', $newRow).val($('#productCategory').val());
    
                    //Replace add button with remove button
                    $('#add', $newRow).addClass('remove').val('Remove').removeClass('btn-success').addClass('btn-danger');
    
                    //remove id attribute from new clone row
                    $('#productCategory,#description,#rate,#add', $newRow).removeAttr('id');
                    $('span.error', $newRow).remove();
                    //append clone row
                    $('#orderdetailsItems').append($newRow);
    
                    //clear select data
                    $('#productCategory').val('0');
                    $('#description,#rate').val('');
                    $('#orderItemError').empty();
                }
    
            })
    
            //remove button click event
            $('#orderdetailsItems').on('click', '.remove', function () {
                $(this).parents('tr').remove();
            });
    
            $('#submit').click(function () {
                debugger;
                var isAllValid = true;
    
                //validate items
                $('#orderItemError').text('');
                var list = [];
                var errorItemCount = 0;
                $('#orderdetailsItems tbody tr').each(function (index, ele) {
                    if (                    
                        $('select.productCategory', this).val() == "0" ||
                        $('.description', this).val() ||
                        $('.rate', this).val() == "" ||
                        isNaN($('.rate', this).val())) {
                        errorItemCount++;
                        $(this).addClass('error');
                    } else {
                        var orderItem = {                        
                            DebitAcHead: $('select.productCategory', this).val(),
                            Description: $('.description', this).val(),
                            Amount: parseFloat($('.rate', this).val())
                        }
                        list.push(orderItem);
                    }
                })
    
                if (errorItemCount > 0) {
                    $('#orderItemError').text(errorItemCount + " invalid entry in order item list.");
                    isAllValid = false;
                }
    
                if (list.length == 0) {
                    $('#orderItemError').text('At least 1  item required.');
                    isAllValid = false;
                }
    
                if (isAllValid) {
                    var data = {
                        MemoDate: $("#memodate").val(),
                        MemoType: $("#momotype").val(),
                        Month: $("#month").val(),
                        FiscalYear: $("#fiscalyear").val(),
                        MemoSubject: $("#memosubject").val(),
                        Amount: $("amount").val(),
                        MemoDetails: $("expensedetails").val(),
                        Justification: $("justification").val(),
                        proposedExpens: list
                    }
    
                    $(this).val('Please wait...');
    
                    $.ajax({
                        type: 'POST',
                        url: '/ExpenditureReq/save',
                        data: JSON.stringify(data),
                        contentType: 'application/json',
                        success: function (data) {
                            if (data.status) {
                                alert('Successfully saved');
                                //here we will clear the form
                                list = [];
                                $('#orderdetailsItems').empty();
                            }
                            else {
                                alert('Error');
                            }
                            $('#submit').text('Save');
                        },
                        error: function (error) {
                            console.log(error);
                            $('#submit').text('Save');
                        }
                    });
                }
    
            });
    
        });
    

    The actual problem is this following part of code , I can not able to push orderItem in list when i execute code the list variable is empty:

     var list = [];
                var errorItemCount = 0;
                $('#orderdetailsItems tbody tr').each(function (index, ele) {
                    if (                    
                        $('select.productCategory', this).val() == "0" ||
                        $('.description', this).val() ||
                        $('.rate', this).val() == "" ||
                        isNaN($('.rate', this).val())) {
                        errorItemCount++;
                        $(this).addClass('error');
                    } else {
                        var orderItem = {                        
                            DebitAcHead: $('select.productCategory', this).val(),
                            Description: $('.description', this).val(),
                            Amount: parseFloat($('.rate', this).val())
                        }
                        list.push(orderItem);
                    }
                })

    I want to add dynamically  selected  value in list:

    the output image is in following link:

    https://drive.google.com/file/d/1PxbpX4icWpPHg_jKbsoUC2RolHvgzNOZ/view?usp=sharing

    I can't  able add added proposed expenses in the list I have write above code and execute but my list is empty how can I solve please check my code and suggest me.

    Saturday, June 6, 2020 10:11 AM

All replies

  • User1535942433 posted

    Hi  jameslovemicrosoft,

    Accroding to your desciption and codes,I have a test.You could press f12 to debug and find it cann't excute else sentence.In the if sentence,$('.description', this).val() is wrong.

    Besides,you must make sure your table have value.

    More details,you could refer to below codes:

    $('#orderdetailsItems tbody tr').each(function (index, ele) {
                       if (                    
                        $('select.productCategory', this).val() == "0" ||
                        $('.description', this).val() == ""||
                        $('.rate', this).val() == "" ||
                        isNaN($('#rate').val())) {
                        errorItemCount++;
                        $(this).addClass('error');
                       } else {
                          
                        var orderItem = {                        
                            DebitAcHead: $('select.productCategory', this).val(),
                            Description: $('.description', this).val(),
                            Amount: parseFloat($('.rate', this).val())
                        }
                        list.push(orderItem);
                    }

    Result:

    Best regards,

    Yijing Sun

    Monday, June 8, 2020 9:19 AM