How to access parent element and then get it's value and then append to other element when adding a row?

My goal is to get the previous value inside my input element labeled "SERIAL END" then automatically append it’s value when adding a row to "SERIAL START" and not only append but will add +1 to it’s value. The problem is I always get an undefine value, I don’t know what is missing.

Here is the image

enter image description here

Here is the snippets

    $(document).ready(function() {
    $("#addrow").on("click", function() {
        var startElement = $("#start");
        var value = parseInt(startElement.val());
        startElement.val(value);
        var hidden = startElement.val();            
        var tbl = document.getElementById('tbl').rows.length;
        if (tbl === 5) {
            alert("It is limited for 5 rows only");
        } else {

            var newRow = $("<tr id='tablerow_" + hidden + "'>");
            var cols = "";

            cols +=
                '<td><select onchange="selectmodel(this)"data-live-search="true" placeholder="Select your model name"id="model' +
                hidden + '" class="form-control selectpicker show-menu-arrow " name="model[]" ><option selected disabled> Select your model name</option><?php $sql = mysqli_query($con,"call gettrial");
            if(mysqli_num_rows($sql)>0){
                while($row=mysqli_fetch_assoc($sql)){
                    echo "<option value=$row[id]>".$row['model_name']." </option>";
                }
            }   ?></select></td>';
            cols +=
                '<td><input id="code' + hidden +
                '" value="" type="text" class="form-control" name="code[]" readonly="" /></td>';
            cols +=
                '<td><input type="number" class="form-control" id="serstart' + hidden +
                '" name="serstart[]" readonly/></td>';
            cols +=
                '<td><input type="number" class="form-control" id="serend' + hidden +
                '" name="serend[]" onkeyup="manage(this)" /></td>';
            newRow.append(cols);
            $("table.order-list").append(newRow)
                .find('.selectpicker')
                .selectpicker({
                    liveSearch: true,
                    showSubtext: true
                });

            const hide = document.getElementById('start');
            hide.value = (parseInt(hidden) + parseInt(1));
            hidden++;
        }
    });
    $('#remove').click(function() {
        $("#myTable").each(function() {
            if ($('tr', this).length > 2) {
                $('tr:last', this).remove();
            }
        });
    });
});

$('#addrow').click(function() {
  var id = $(this).closest('tr').find('#tablerow_0').text();
  var row = $(this).parent("tbody tr");
  var rowin=$(this).parent('tr').find('input:number');
  var rowprev=$(this).parent('tr').prev().find('input:last').val();
  var rownext=$(this).parent('tr').next().find('input:first').val();
  console.log($(this).parent('tr').prev().find('input:last'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-lg-12">
     <form class="className" name="form" id="form"
      action="lot_registration_model_submit.php" data-toggle="validator"
      enctype="multipart/form-data" method="POST">
       <div class="form-group">
            <label class="col-sm-3">Lot No.: <font color="red">*</font></label>
            <div class="col-sm-9">
                 <input autocomplete="off" class="form-control" type="text" id="lotno"
                  name="lotno" style="text-transform:uppercase" required>
            </div>
       </div>
<div class="form-group">
    <label class="col-sm-3">Month of: <font color="red">*</font></label>
      <div class="col-sm-9">
       <input autocomplete="off" class="form-control" type="date" id="monthof"
        name="monthof" style="text-transform:uppercase" required>
      </div>
</div>

<div class="form-group">
  <label class="col-sm-3">Serial Start: <font color="red">*</font></label>
   <div class="col-sm-9">
     <input autocomplete="off" class="form-control" type="number" id="serstart" name="serstart" 
      style="text-transform:uppercase" required>
   </div>
</div>

 <div class="form-group">
    <label class="col-sm-3">Serial End: <font color="red">*</font></label>
      <div class="col-sm-9">
        <input autocomplete="off" class="form-control" type="number" id="serend"
         name="serend" style="text-transform:uppercase" required>
      </div>
 </div>

 <input type="button" class="btn btn-primary pull-left" id="addrow" value="Add Row" disabled />&nbsp;
 <input type="button" class="ibtnDel btn btn-md btn-danger" id="remove" value="Delete Row">
 <br>&nbsp;
    <table width="100%" class="table order-list table-striped table-bordered table-hover" 
     id="myTable">
     <thead>
      <tr>
       <th class="col-sm-3">
           <center />Model
       </th>
       <th class="col-sm-3">
           <center />Code
       </th>
       <th class="col-sm-3">
           <center />Serial Start
       </th>
       <th class="col-sm-3">
           <center />Serial End
       </th>
      </tr>
     </thead>

     <tbody id='tbl'>
      <tr id="tablerow_0">
       <td>
        <select name="model[]" id="model0" class="form-control selectpicker show-menu-arrow"
         data-live-search="true" title="Select your model name"
         onchange="selectmodel(this)" required>

        <?php

          $sql = mysqli_query($con,"SELECT model.id,model.model_name,model.code,model.status
           FROM model left join grouped on model.id = grouped.modelandcode
           WHERE cat_id='1' and model.status='1' and grouped.status is null 
           ORDER BY model_name ASC"); 
           $con->next_result();
           if(mysqli_num_rows($sql)>0)
           {
              while($row=mysqli_fetch_assoc($sql))
              {
              echo "<option value='".$row['id']."'>".$row['model_name']."</option>";
              }
          }   
         ?>
        </select>
       </td>

       <td>
       <input name="code[]" type="text" id="code0" value="" class="form-control" readonly="" />
       </td>
       <td>
       <input type="number" name="serstart[]" id="serstart0" class="form-control" readonly />
       </td>
       <td>
       <input type="number" name="serend[]" id="serend0" class="form-control" 
      </td>
      </tr>
     </tbody>
   </table>

   <input type="hidden" value="1" id="start" />
    <button id="submit" type="submit" class="btn btn-primary pull-right"><span
     class="fa  fa-check"> &nbsp Submit</span></button>
  </form>
</div>

10 thoughts on “How to access parent element and then get it's value and then append to other element when adding a row?”

  1. You can get length of tr inside tbody then using that length get reference of previous tr then use td:eq(3) this will search fourth td because index starts from 0 then use that value to get value and add it in newly created tr input .

    Also , you don’t need to use same php code to create select-box just clone first select-box and then use same to pass inside td which are newly created .

    Then , to intialize selectpicker which are added dynamically use $("table.order-list tr:last").find(".selectpicker").. this line will get last tr which is added and then inside that tr it will selectpicker .

    Demo Code :

    $(document).ready(function() {
      $('.selectpicker').selectpicker({
        liveSearch: true,
        showSubtext: true
      });
      $("#addrow").on("click", function() {
        var cloned = $("tbody select:first").clone() //cloned first tr select
        var value = $("tbody tr").length - 1 //get tr length - 1 (because tr start from 0 index)
        var new_start = parseInt($("tbody tr:eq(" + value + ") td:eq(3) input").val()) + 1 //get previous input box value
        var tbl = document.getElementById('tbl').rows.length;
        if (tbl === 5) {
          alert("It is limited for 5 rows only");
        } else {
    
          var newRow = $("<tr id='tablerow_'" + (value + 1) + "'>");
          var cols = "";
          cols += '<td><select onchange="selectmodel(this)"data-live-search="true" placeholder="Select your model name" class="form-control selectpicker show-menu-arrow " name="model[]" >' + $(cloned).html() + '</select></td>';
          cols += '<td><input value="' + $("#lotno").val() + '" type="text" class="form-control" name="code[]" readonly="" /></td>';
          cols +=
            '<td><input type="number" class="form-control" name="serstart[]" value="' + new_start + '" readonly/></td>';
          cols +=
            '<td><input type="number" class="form-control"name="serend[]"  value="' + $("#serend").val() + '"/></td>';
          newRow.append(cols);
          $("table.order-list").append(newRow)
          //intialize selectpicker which added last
          $("table.order-list tr:last").find('.selectpicker').selectpicker({
            liveSearch: true,
            showSubtext: true
          });
        }
      });
    });
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.18/css/bootstrap-select.min.css" integrity="sha512-ARJR74swou2y0Q2V9k0GbzQ/5vJ2RBSoCWokg4zkfM29Fb3vZEQyv0iWBMW/yvKgyHSR/7D64pFMmU8nYmbRkg==" crossorigin="anonymous"
    />
    <script src="https://code.jquery.com/jquery-3.5.0.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.18/js/bootstrap-select.min.js" integrity="sha512-yDlE7vpGDP7o2eftkCiPZ+yuUyEcaBwoJoIhdXv71KZWugFqEphIS3PU60lEkFaz8RxaVsMpSvQxMBaKVwA5xg==" crossorigin="anonymous"></script>
    <div class="col-lg-12">
    
    
      <input type="button" class="btn btn-primary pull-left" id="addrow" value="Add Row" />&nbsp;
      <input type="button" class="ibtnDel btn btn-md btn-danger" id="remove" value="Delete Row">
      <br>&nbsp;
      <table width="100%" class="table order-list table-striped table-bordered table-hover" id="myTable">
        <thead>
          <tr>
            <th class="col-sm-3">
              <center />Model
            </th>
            <th class="col-sm-3">
              <center />Code
            </th>
            <th class="col-sm-3">
              <center />Serial Start
            </th>
            <th class="col-sm-3">
              <center />Serial End
            </th>
          </tr>
        </thead>
    
        <tbody id='tbl'>
          <tr id="tablerow_0">
            <td>
              <select name="model[]" id="model0" class="form-control selectpicker show-menu-arrow" data-live-search="true" title="Select your model name" onchange="selectmodel(this)" required>
              <option selected disabled> Select your model name</option>
                <option value='1'>A</option>
                <option value='2'>A2</option>
                <option value='3'>A3</option>
              </select>
            </td>
    
            <td>
              <input name="code[]" type="text" id="code0" value="M12" class="form-control" readonly="" />
            </td>
            <td>
              <input type="number" name="serstart[]" id="serstart0" value="1" class="form-control" readonly />
            </td>
            <td>
              <input type="number" name="serend[]" id="serend0" value="11" class="form-control"> </td>
          </tr>
        </tbody>
      </table>
      <button id="submit" type="submit" class="btn btn-primary pull-right"><span
         class="fa  fa-check"> &nbsp Submit</span></button>
      </form>
    </div>
    Reply

Leave a Comment