skip to Main Content

I have created a form and in the form I have given room to clone input fields ie add or delete rows.
In one input field I am using Jquery Ajax to get the value.
Unfortunately after adding an additional role ie cloning the parent row to get a child row, ajax does not pass the value for the input field expecting it value from the Ajax.

I have attached the code below to explain better

function restrictAlphabets(e) {
  var x = e.which || e.keyCode;
  if ((x >= 48 && x <= 57))
    return true;
  else
    return false;
}

// Below Clones Table
document.querySelector('button[data-name="add"]').addEventListener('click', e => {
  let tbody = e.target.closest('table').querySelector('tbody');
  let clone = tbody.firstElementChild.cloneNode(true);
  clone.querySelector('button[data-name="del"]').hidden = false;
  clone.querySelectorAll('input, select').forEach(n => {
    n.value = '';
  });
  tbody.appendChild(clone);

});
document.querySelector('form table#dyntbl').addEventListener('click', e => {
  e.stopPropagation();
  if (e.target != e.currentTarget && (e.target.dataset.name == 'del' || e.target.parentNode.dataset.name == 'del')) {
    let tbody = e.target.closest('table').querySelector('tbody');
    if (tbody.childNodes.length > 3) tbody.removeChild(e.target.closest('tr'))
  }
});
// Below begins AJAX Function
function checkDeviceStatus() {
  var dModel = $("#model").val();
  var dBrand = $("#brand").val();
  var dserial = $("#serialNo").val();
  var client = $("#client").val();

  $.ajax({
    url: "./handlers/slaChecker.php",
    type: "POST",
    data: {
      dModel: dModel,
      dserial: dserial,
      client: client,
      dBrand: dBrand,
    },
    success: function(result) {
      $("#deviceLevel").val(result);
      console.log(result);
    }
  })
}
<div class="col-xl-8 col-md-12">
  <form>
    <div class="card">
      <div class="card-header">
        <h3 class="card-title"><strong class="text-success" style="cursor: pointer;"><?=ucwords($clientName)?></strong> REP'S INFORMATION</h3>
      </div>
      <div class="card-body">
        <div class="row">
          <div class="col-sm-4 col-md-4">
            <div class="form-group">
              <label class="form-label">Reps Name<span class="text-red">*</span></label>
              <input type="text" name="" class="form-control" required="">
            </div>
          </div>
          <div class="col-sm-4 col-md-4">
            <div class="form-group">
              <label class="form-label">E-Mail<span class="text-red">*</span></label>
              <input type="email" name="" class="form-control" required="">
            </div>
          </div>
          <div class="col-sm-4 col-md-4">
            <div class="form-group">
              <label class="form-label">Phone No.<span class="text-red">*</span></label>
              <input type="text text-dark" class="form-control" name="client_contact2" required="" id="client_contact2" onkeypress="return restrictAlphabets(event)" onpaste="return false;" ondrop="return false;" autocomplete="off" required="">
              <input type="date" name="" value="<?=date(" Y-m-d ")?>" hidden="">
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="card">
      <div class="card-header">
        <h3 class="card-title">ADD DEVICE(S) INFORMATION</h3>
      </div>
      <div class="card-body">
        <?php 
                        if ($clientType === $slaClient) {
                    ?>
        <table id='dyntbl' class='table border text-nowrap text-md-nowrap table-striped mb-0'>
          <thead>
            <tr>
              <th class="text-center">Device Brand</th>
              <th class="text-center">Device Model</th>
              <th class="text-center">Serial Number</th>
              <th class="text-center" style="width:10%">SLA Device</th>
              <th><button type="button" class=" btn text-success" data-name='add'><i class="fe fe-plus-circle" data-id='ad' style="font-size:1.6em;"></i></button></th>
            </tr>
          </thead>
          <tbody class="field_wrapper " id="table_body">
            <tr>
              <td>
                <select class="form-control form-select " data-bs-placeholder="Select" name="brand[]" required="" id="brand" onchange="checkDeviceStatus()">
                  <?php 
                         $readALL = "SELECT * FROM productbrands WHERE deleted = 0";
                         $displayAll = mysqli_query($conn,$readALL);
                         while($rowFetchAll = mysqli_fetch_array($displayAll)){
                          $brandName = $rowFetchAll['brandName'];
                          $brandid = $rowFetchAll['brandID'];
                        ?>
                  <option value="<?=$brandid?>">
                    <?=$brandName?>
                  </option>
                  <?php } ?>
                </select>
              </td>
              <td>
                <select class="form-control form-select " data-bs-placeholder="Select" name="model[]" required="" id="model" onchange="checkDeviceStatus()">
                  <?php 
                       $readALL1 = "SELECT * FROM productmodels WHERE deleted = 0";
                       $displayAll1 = mysqli_query($conn,$readALL1);
                       while($rowFetchAll1 = mysqli_fetch_array($displayAll1)){
                        $modelName = $rowFetchAll1['modelName'];
                        $modelid = $rowFetchAll1['modelID'];
                      ?>
                  <option value="<?=$modelid?>">
                    <?=$modelName?>
                  </option>
                  <?php } ?>
                </select>
              </td>
              <td><input type="text" name="serialNo" class="form-control" id="serialNo" onchange="checkDeviceStatus()"></td>
              <!-- The input field below is to get value from AJAX -->
              <td><input type="text" name="deviceLevel" class="form-control" readonly="" id="deviceLevel">
                <!-- End of Input field -->
              </td>
              <input type="text" name="" id="client" value="<?=$clientID?>" hidden="">
              <td><button type="button" class=" btn text-danger" data-name="del"><i class="fe fe-minus-circle"  style="font-size:1.6em;"></i></button></td>
            </tr>
          </tbody>
        </table>
        <?php } ?>
        <?php
                        if ($clientType === $nonSla) {
                    ?>
          <table id='dyntbl' class='table border text-nowrap text-md-nowrap table-striped mb-0'>
            <thead>
              <tr>
                <th>Product Model Non-SLA</th>
                <th>Serial Number Non-SLA</th>
                <th>Device Status Non-SLA</th>
                <th><button type="button" class=" btn text-success" data-name='add'><i class="fe fe-plus-circle" data-id='ad' style="font-size:1.6em;"></i></button></th>
              </tr>
            </thead>
            <tbody class="field_wrapper " id="table_body">
              <tr>
                <td><input type="text" name="" class="form-control"></td>
                <td><input type="text" name="" class="form-control"></td>
                <td><input type="text" name="" class="form-control"></td>
                <td><button type="button" class=" btn text-danger" data-name="del"><i class="fe fe-minus-circle"  style="font-size:1.6em;"></i></button></td>
              </tr>
            </tbody>
          </table>
          <?php } ?>
      </div>
    </div>
  </form>
</div>

2

Answers


  1. Chosen as BEST ANSWER

    I have found solution to it. The classes as you all suggested wasn't Ideal instead this is what I did. the ids has to be unique so I created a variable for it to be handling the additional ids. This worked perfectly for me. Php is now working fine and Ajax is also working fine.

    $(document).ready(function() {
      var num = 1;
      var c = `
                        <tr id="row_num" >
                           <td>
                              <select class="form-control form-select brand" data-bs-placeholder="Select" name="brand[]" required="" id="brand_num" onchange="checkDeviceStatus(_num)">
                                 <?php 
                                    $readALL = "SELECT * FROM productbrands WHERE deleted = 0";
                                    $displayAll = mysqli_query($conn,$readALL);
                                    while($rowFetchAll = mysqli_fetch_array($displayAll)){
                                     $brandName = $rowFetchAll['brandName'];
                                     $brandid = $rowFetchAll['brandID'];
                                    ?>
                                 <option value="<?=$brandid?>"><?=$brandName?></option>
                                 <?php } ?>
                              </select>
                           </td>
                           <td>
                              <select class="form-control form-select model" data-bs-placeholder="Select" name="model[]" required="" id="model_num" onchange="checkDeviceStatus(_num)">
                                 <?php 
                                    $readALL1 = "SELECT * FROM productmodels WHERE deleted = 0";
                                    $displayAll1 = mysqli_query($conn,$readALL1);
                                    while($rowFetchAll1 = mysqli_fetch_array($displayAll1)){
                                     $modelName = $rowFetchAll1['modelName'];
                                     $modelid = $rowFetchAll1['modelID'];
                                    ?>
                                 <option value="<?=$modelid?>"><?=$modelName?></option>
                                 <?php } ?>
                              </select>
                           </td>
                           <td><input type="text" name="serialNo" class="form-control serialNo" id="serialNo_num" onkeyup="checkDeviceStatus(_num)"></td>
                           <!-- The input field below is to get value from AJAX -->
                           <td>
                              <input type="text" name="deviceLevel" class="form-control " readonly="" id="deviceLevel_num"> 
                              <!-- End of Input field -->
                           </td>
                           <td><button type="button" onclick="DeleteRow(_num)" class=" btn text-danger remove" data-name="del"><i class="fe fe-minus-circle"  style="font-size:1.6em;"></i></button></td>
                        </tr>
                        `;
      $(".addRow").click(function(e) {
        var cc = c;
        // e.preventDefault();
        cc = cc.replace('_num', num);
        cc = cc.replace('_num', num);
        cc = cc.replace('_num', num);
        cc = cc.replace('_num', num);
        cc = cc.replace('_num', num);
        cc = cc.replace('_num', num);
        cc = cc.replace('_num', num);
        cc = cc.replace('_num', num);
        cc = cc.replace('_num', num);
        $(".table_body").append(cc);
        num++;
        console.log(num);
      });
    });
    <tbody class="field_wrapper showRow table_body" id="table_body">
      <tr id="row0">
        <td>
          <select class="form-control form-select" data-bs-placeholder="Select" name="brand[]" required="" id="brand0" onchange="checkDeviceStatus(0)">
            <?php 
                             $readALL = "SELECT * FROM productbrands WHERE deleted = 0";
                             $displayAll = mysqli_query($conn,$readALL);
                             while($rowFetchAll = mysqli_fetch_array($displayAll)){
                              $brandName = $rowFetchAll['brandName'];
                              $brandid = $rowFetchAll['brandID'];
                            ?>
            <option value="<?=$brandid?>">
              <?=$brandName?>
            </option>
            <?php } ?>
          </select>
        </td>
        <td>
          <select class="form-control form-select " data-bs-placeholder="Select" name="model[]" required="" id="model0" onchange="checkDeviceStatus(0)">
            <?php 
                           $readALL1 = "SELECT * FROM productmodels WHERE deleted = 0";
                           $displayAll1 = mysqli_query($conn,$readALL1);
                           while($rowFetchAll1 = mysqli_fetch_array($displayAll1)){
                            $modelName = $rowFetchAll1['modelName'];
                            $modelid = $rowFetchAll1['modelID'];
                          ?>
            <option value="<?=$modelid?>">
              <?=$modelName?>
            </option>
            <?php } ?>
          </select>
        </td>
        <td><input type="text" name="serialNo" class="form-control " id="serialNo0" onkeyup="checkDeviceStatus(0)"></td>
        <!-- The input field below is to get value from AJAX -->
        <td><input type="text" name="deviceLevel" class="form-control " readonly="" id="deviceLevel0">
          <!-- End of Input field -->
        </td>
        <input type="text" name="" id="client" value="<?=$clientID?>" hidden="">
        <td><button type="button" class=" btn text-success addRow" data-name='add'><i class="fe fe-plus-circle " data-id='ad' style="font-size:1.6em;"></i></button></td>
      </tr>
    </tbody>


  2. The main problem is that when you clone, you will get duplicated id’s. An Id must always be unique.

    I would suggest that you change the ID to class or something else and do something like this.

    function checkDeviceStatus(obj) {
      var dModel = $(obj).closest("tr").find(".model").val();
      var dBrand = $(obj).closest("tr").find(".brand").val();
      var dserial = $(obj).closest("tr").find(".serialNo").val();
      var client = $(obj).closest("tr").find(".client").val();
    
      console.log("dserial:"+dserial);
    
      //Removed ajax for demo.
    }
    

    And then add this to your onchange="checkDeviceStatus()" like onchange="checkDeviceStatus(this)"

    Demo

    function restrictAlphabets(e) {
      var x = e.which || e.keyCode;
      if ((x >= 48 && x <= 57))
        return true;
      else
        return false;
    }
    
    // Below Clones Table
    document.querySelector('button[data-name="add"]').addEventListener('click', e => {
      let tbody = e.target.closest('table').querySelector('tbody');
      let clone = tbody.firstElementChild.cloneNode(true);
      clone.querySelector('button[data-name="del"]').hidden = false;
      clone.querySelectorAll('input, select').forEach(n => {
        n.value = '';
      });
      tbody.appendChild(clone);
    
    });
    document.querySelector('form table#dyntbl').addEventListener('click', e => {
      e.stopPropagation();
      if (e.target != e.currentTarget && (e.target.dataset.name == 'del' || e.target.parentNode.dataset.name == 'del')) {
        let tbody = e.target.closest('table').querySelector('tbody');
        if (tbody.childNodes.length > 3) tbody.removeChild(e.target.closest('tr'))
      }
    });
    // Below begins AJAX Function
    function checkDeviceStatus(obj) {
      var dModel = $(obj).closest("tr").find(".model").val();
      var dBrand = $(obj).closest("tr").find(".brand").val();
      var dserial = $(obj).closest("tr").find(".serialNo").val();
      var client = $(obj).closest("tr").find(".client").val();
    
      console.log("dserial:"+dserial);
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="col-xl-8 col-md-12">
      <form>
        <div class="card">
          <div class="card-header">
            <h3 class="card-title"><strong class="text-success" style="cursor: pointer;"><?=ucwords($clientName)?></strong> REP'S INFORMATION</h3>
          </div>
          <div class="card-body">
            <div class="row">
              <div class="col-sm-4 col-md-4">
                <div class="form-group">
                  <label class="form-label">Reps Name<span class="text-red">*</span></label>
                  <input type="text" name="" class="form-control" required="">
                </div>
              </div>
              <div class="col-sm-4 col-md-4">
                <div class="form-group">
                  <label class="form-label">E-Mail<span class="text-red">*</span></label>
                  <input type="email" name="" class="form-control" required="">
                </div>
              </div>
              <div class="col-sm-4 col-md-4">
                <div class="form-group">
                  <label class="form-label">Phone No.<span class="text-red">*</span></label>
                  <input type="text text-dark" class="form-control" name="client_contact2" required="" id="client_contact2" onkeypress="return restrictAlphabets(event)" onpaste="return false;" ondrop="return false;" autocomplete="off" required="">
                  <input type="date" name="" value="<?=date(' Y-m-d ')?>" hidden="">
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="card">
          <div class="card-header">
            <h3 class="card-title">ADD DEVICE(S) INFORMATION</h3>
          </div>
          <div class="card-body">
            <?php 
                            if ($clientType === $slaClient) {
                        ?>
            <table id='dyntbl' class='table border text-nowrap text-md-nowrap table-striped mb-0'>
              <thead>
                <tr>
                  <th class="text-center">Device Brand</th>
                  <th class="text-center">Device Model</th>
                  <th class="text-center">Serial Number</th>
                  <th class="text-center" style="width:10%">SLA Device</th>
                  <th><button type="button" class=" btn text-success" data-name='add'><i class="fe fe-plus-circle" data-id='ad' style="font-size:1.6em;">ADD</i></button></th>
                </tr>
              </thead>
              <tbody class="field_wrapper " id="table_body">
                <tr>
                  <td>
                    <select class="form-control form-select brand" data-bs-placeholder="Select" name="brand[]" required="" id="" onchange="checkDeviceStatus(this)">
                      <?php 
                             $readALL = "SELECT * FROM productbrands WHERE deleted = 0";
                             $displayAll = mysqli_query($conn,$readALL);
                             while($rowFetchAll = mysqli_fetch_array($displayAll)){
                              $brandName = $rowFetchAll['brandName'];
                              $brandid = $rowFetchAll['brandID'];
                            ?>
                      <option value="<?=$brandid?>">
                        <?=$brandName?>
                      </option>
                      <?php } ?>
                    </select>
                  </td>
                  <td>
                    <select class="form-control form-select model" data-bs-placeholder="Select" name="model[]" required="" id="" onchange="checkDeviceStatus(this)">
                      <?php 
                           $readALL1 = "SELECT * FROM productmodels WHERE deleted = 0";
                           $displayAll1 = mysqli_query($conn,$readALL1);
                           while($rowFetchAll1 = mysqli_fetch_array($displayAll1)){
                            $modelName = $rowFetchAll1['modelName'];
                            $modelid = $rowFetchAll1['modelID'];
                          ?>
                      <option value="<?=$modelid?>">
                        <?=$modelName?>
                      </option>
                      <?php } ?>
                    </select>
                  </td>
                  <td><input type="text" name="serialNo" class="form-control serialNo"  onchange="checkDeviceStatus(this)"></td>
                  <!-- The input field below is to get value from AJAX -->
                  <td><input type="text" name="deviceLevel" class="form-control" readonly="" id="deviceLevel">
                    <!-- End of Input field -->
                  </td>
                  <input type="text" name="" class="client" value="<?=$clientID?>" hidden="">
                  <td><button type="button" class=" btn text-danger" data-name="del"><i class="fe fe-minus-circle"  style="font-size:1.6em;"></i></button></td>
                </tr>
              </tbody>
            </table>
            <?php } ?>
            <?php
                            if ($clientType === $nonSla) {
                        ?>
              <table id='dyntbl' class='table border text-nowrap text-md-nowrap table-striped mb-0'>
                <thead>
                  <tr>
                    <th>Product Model Non-SLA</th>
                    <th>Serial Number Non-SLA</th>
                    <th>Device Status Non-SLA</th>
                    <th><button type="button" class=" btn text-success" data-name='add'><i class="fe fe-plus-circle" data-id='ad' style="font-size:1.6em;"></i></button></th>
                  </tr>
                </thead>
                <tbody class="field_wrapper " id="table_body">
                  <tr>
                    <td><input type="text" name="" class="form-control"></td>
                    <td><input type="text" name="" class="form-control"></td>
                    <td><input type="text" name="" class="form-control"></td>
                    <td><button type="button" class=" btn text-danger" data-name="del"><i class="fe fe-minus-circle"  style="font-size:1.6em;"></i></button></td>
                  </tr>
                </tbody>
              </table>
              <?php } ?>
          </div>
        </div>
      </form>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search