Sanjit Bhardwaj
Sanjit Bhardwaj

Reputation: 893

dynamic ajax populate issue

enter image description here

I am facing problem in populating the select field of html by ajax.

At the loading of the page , there is only one row . On selecting a course from the course field via ajax i have taken the id and populate it with respective board.But when i insert a new row by appending the table , the course and branch field does not populate as the code is written .

Please Check the code

     $('#myTable').on('click', 'input[type="button"]', function () {
            $(this).closest('tr').remove();
        })
        var html = "";
        html += '<tr>';
        html += '<td><select class= "form-control" name="course[]"  id="course"  style="width: 200px">';
        html += '<option value="">--SELECT COURSE --</option>';
        html += '<?php foreach ($courseList as $key => $value) { ?>';
            html += '<option value="<?php echo $value['id']; ?>"><?php echo $value['c_name']; ?></option>';
            html += '<?php } ?>';
        html += '</select>';
        html += '</td>';
        html += '<td><select class= "form-control" name="branch[]"  id="branch" style="width: 200px"></select>';
        html += '</td>';
        html += '<td><input type="number"  class="form-control" name="course_fee[]" placeholder="Course Fee" autocomplete="off" required=""></td>';
        html += '<td><input type="number"  class="form-control" name="discount_per[]" placeholder="Discount Percent" autocomplete="off" required=""></td>';
        html += '<td><input type="number"  class="form-control" name="total_seats[]" placeholder="Total Seats" autocomplete="off" required=""></td>';
        html += '<td><input type="text"  class="form-control stime" name="start_session[]" placeholder="Start Session" autocomplete="off" required=""></td>';
        html += '<td><input type="text"  class="form-control etime" name="end_session[]" placeholder="End Session" autocomplete="off" required=""></td>';
        html += '<td>';
        html += '<input type="button" class="btn btn-danger" value="Delete" />';
        html += '</td>';
        html += '</tr>';
        $('p input[type="button"]').click(function () {
            $('#myTable').append(html);
        });

 $(document).on('change', '#course', function () {
            //alert("ssss");
            fetch_select(this);
        })

        function fetch_select(val)
        {

            //console.log(val.value);
            $.ajax({
                type: 'post',
                url: 'common/ajax.function.php',
                data: {
                    course_id: val.value, course: "select_course"
                },
                success: function (response) {
                    //console.log(response); 
                    var html = "";
                    var data = JSON.parse(response);
                    //console.log(data);
                    if (data !== '') {
                        $.each(data, function (key, value) {
                            html += ' <option name="branch_id" id="' + value['id'] + '" value="' + value['id'] + '">' + value['branch_name'] + '</option>';
                        })
                    } else {
                        $("#branch").prop("disabled", "true");
                    }
                    //$(val).closest('select').html(html);
                    //$(val).next().html(html);
                    $("td").siblings("td").children("#branch").html(html);
                    //$("#branch").html(html);
                    //document.getElementById("new_select").innerHTML = response;
                }
            });
        }

The php code is

<table id="myTable" class="data datatable table table-striped table-bordered table-hover" id="institution">  
                                    <thead>  
                                        <tr>  
                                            <th style="width:0px">Course</th>
                                            <th>Branch</th>
                                            <th>Course Fee</th> 
                                            <th>Discount Percent</th>
                                            <th>Total Seats</th>
                                            <th>Start Session</th>
                                            <th>End Session</th>
                                        </tr>  
                                    </thead>  
                                    <tbody>
                                        <tr>
                                            <td><select class= "form-control" name="course[]"  id="course" style="width: 200px" >
                                                    <option value="">--SELECT COURSE --</option>
                                                    <?php foreach ($courseList as $key => $value) { ?>
                                                        <option value="<?php echo $value['id']; ?>"><?php echo $value['c_name']; ?></option>
                                                    <?php } ?>
                                                </select>
                                            </td>
                                            <td  ><select class= "form-control" name="branch[]"  id="branch" style="width: 200px">
                                                </select></td>
                                            <td><input type="number"  class="form-control" name="course_fee[]" placeholder="Course Fee" autocomplete="off" required=""></td>
                                            <td><input type="number"  class="form-control" name="discount_per[]" placeholder="Discount Percent" autocomplete="off" required=""></td>
                                            <td><input type="number"  class="form-control" name="total_seats[]" placeholder="Total Seats" autocomplete="off" required=""></td>
                                            <td><input type="text"  class="form-control stime" name="start_session[]" placeholder="Start Session" autocomplete="off" required=""></td>
                                            <td><input type="text"  class="form-control etime" name="end_session[]" placeholder="End Session" autocomplete="off" required=""></td>
                                            <td>
                                                <input type="button" class="btn btn-danger" value="Delete" />
                                            </td>
                                        </tr>

                                    </tbody>
                                </table>
                                <br>
                                <p style="float: right">
                                    <input type="button" value="Insert row &darr;">
                                </p>

Upvotes: 0

Views: 77

Answers (1)

Ravenous
Ravenous

Reputation: 1160

Please note that IDs must be unique in your page, if you keep on repeating IDs, mark-up validators will scream when they will scan your page and your JavaScript will never work as intended.

First of all, composing table rows with HTML in this brutal way is wrong. You either need to:

  1. come up with a more systematic way of doing so
  2. rely on the server to send you a full row and just append it to the existing ones
  3. clone the existing rows but make sure not to repeat IDs (even if you won't need to access IDs as you can easily spot the position of a row using DOM tree, IDs must be unique)

Assuming you add the class course to the course select, instead of the ID, you need to find out what row needs to get updated. For this, you want to know the change event target. So, you would do

$(document).on('change', '.course', function(event) {
    let target = $(event.target);
    // ajax logic here that will result in a string containing the options, I called it ajaxResult
    target.siblings('.branch').html(ajaxResult);
}

Note 1: Please note that I've also changed #branch to .branch
Note 2: Please note that you are appending PHP code at

$('p input[type="button"]').click(function () {
    $('#myTable').append(html);
});

Upvotes: 1

Related Questions