Home > OS >  OnChange Not Working in cloned Input fields
OnChange Not Working in cloned Input fields

Time:08-27

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 >
  <form>
    <div >
      <div >
        <h3 ><strong  style="cursor: pointer;"><?=ucwords($clientName)?></strong> REP'S INFORMATION</h3>
      </div>
      <div >
        <div >
          <div >
            <div >
              <label >Reps Name<span >*</span></label>
              <input type="text" name=""  required="">
            </div>
          </div>
          <div >
            <div >
              <label >E-Mail<span >*</span></label>
              <input type="email" name=""  required="">
            </div>
          </div>
          <div >
            <div >
              <label >Phone No.<span >*</span></label>
              <input type="text text-dark"  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 >
      <div >
        <h3 >ADD DEVICE(S) INFORMATION</h3>
      </div>
      <div >
        <?php 
                        if ($clientType === $slaClient) {
                    ?>
        <table id='dyntbl' class='table border text-nowrap text-md-nowrap table-striped mb-0'>
          <thead>
            <tr>
              <th >Device Brand</th>
              <th >Device Model</th>
              <th >Serial Number</th>
              <th  style="width:10%">SLA Device</th>
              <th><button type="button"  data-name='add'><i  data-id='ad' style="font-size:1.6em;"></i></button></th>
            </tr>
          </thead>
          <tbody  id="table_body">
            <tr>
              <td>
                <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  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"  id="serialNo" onchange="checkDeviceStatus()"></td>
              <!-- The input field below is to get value from AJAX -->
              <td><input type="text" name="deviceLevel"  readonly="" id="deviceLevel">
                <!-- End of Input field -->
              </td>
              <input type="text" name="" id="client" value="<?=$clientID?>" hidden="">
              <td><button type="button"  data-name="del"><i   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"  data-name='add'><i  data-id='ad' style="font-size:1.6em;"></i></button></th>
              </tr>
            </thead>
            <tbody  id="table_body">
              <tr>
                <td><input type="text" name="" ></td>
                <td><input type="text" name="" ></td>
                <td><input type="text" name="" ></td>
                <td><button type="button"  data-name="del"><i   style="font-size:1.6em;"></i></button></td>
              </tr>
            </tbody>
          </table>
          <?php } ?>
      </div>
    </div>
  </form>
</div>

CodePudding user response:

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 >
  <form>
    <div >
      <div >
        <h3 ><strong  style="cursor: pointer;"><?=ucwords($clientName)?></strong> REP'S INFORMATION</h3>
      </div>
      <div >
        <div >
          <div >
            <div >
              <label >Reps Name<span >*</span></label>
              <input type="text" name=""  required="">
            </div>
          </div>
          <div >
            <div >
              <label >E-Mail<span >*</span></label>
              <input type="email" name=""  required="">
            </div>
          </div>
          <div >
            <div >
              <label >Phone No.<span >*</span></label>
              <input type="text text-dark"  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 >
      <div >
        <h3 >ADD DEVICE(S) INFORMATION</h3>
      </div>
      <div >
        <?php 
                        if ($clientType === $slaClient) {
                    ?>
        <table id='dyntbl' class='table border text-nowrap text-md-nowrap table-striped mb-0'>
          <thead>
            <tr>
              <th >Device Brand</th>
              <th >Device Model</th>
              <th >Serial Number</th>
              <th  style="width:10%">SLA Device</th>
              <th><button type="button"  data-name='add'><i  data-id='ad' style="font-size:1.6em;">ADD</i></button></th>
            </tr>
          </thead>
          <tbody  id="table_body">
            <tr>
              <td>
                <select  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  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"   onchange="checkDeviceStatus(this)"></td>
              <!-- The input field below is to get value from AJAX -->
              <td><input type="text" name="deviceLevel"  readonly="" id="deviceLevel">
                <!-- End of Input field -->
              </td>
              <input type="text" name=""  value="<?=$clientID?>" hidden="">
              <td><button type="button"  data-name="del"><i   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"  data-name='add'><i  data-id='ad' style="font-size:1.6em;"></i></button></th>
              </tr>
            </thead>
            <tbody  id="table_body">
              <tr>
                <td><input type="text" name="" ></td>
                <td><input type="text" name="" ></td>
                <td><input type="text" name="" ></td>
                <td><button type="button"  data-name="del"><i   style="font-size:1.6em;"></i></button></td>
              </tr>
            </tbody>
          </table>
          <?php } ?>
      </div>
    </div>
  </form>
</div>

CodePudding user response:

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  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  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"  id="serialNo_num" onkeyup="checkDeviceStatus(_num)"></td>
                       <!-- The input field below is to get value from AJAX -->
                       <td>
                          <input type="text" name="deviceLevel"  readonly="" id="deviceLevel_num"> 
                          <!-- End of Input field -->
                       </td>
                       <td><button type="button" onclick="DeleteRow(_num)"  data-name="del"><i   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  id="table_body">
  <tr id="row0">
    <td>
      <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  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"  id="serialNo0" onkeyup="checkDeviceStatus(0)"></td>
    <!-- The input field below is to get value from AJAX -->
    <td><input type="text" name="deviceLevel"  readonly="" id="deviceLevel0">
      <!-- End of Input field -->
    </td>
    <input type="text" name="" id="client" value="<?=$clientID?>" hidden="">
    <td><button type="button"  data-name='add'><i  data-id='ad' style="font-size:1.6em;"></i></button></td>
  </tr>
</tbody>

  • Related