Add Row dynamically with SelectPicker Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Add Row dynamically with SelectPicker without wasting too much if your time.

The question is published on by Tutorial Guruji team.

Morning,

I have a table with selectpicker in first column. and i would like to add dynamically rows. Actually after adding row first column it’s ok but i can’t select for second column. Thks for your help.

My table :

<tbody>
    <tr>
        <td>
            <Select class="selectpicker" name="item_desc[]" id="item_desc" type="integer" onchange="select_fields(this)">
                <option> </option>
                @foreach ($articles as $article)
                    <option>{{$article->id}}</option>
                @endforeach
            </Select>
        </td>
        <td class="writefields" name="item_fields[]"></td>
        <td><i class="btn far fa-trash-alt" onclick="remove_row(this)"></i></td>
    </tr>
</tbody>

`

My function to add row :

function add_row(){
     var root = document.getElementById('add_table').getElementsByTagName('tbody')[0];
     var rows = root.getElementsByTagName('tr');
     var clone = cloneEl(rows[rows.length -1]);
     cleanUpInputs(clone);
     root.appendChild(clone);
 }

 function cloneEl(el){
     var clo = el.cloneNode(true);
     return clo;
 }

 function cleanUpInputs(obj){
     for (var i = 0; n = obj.childNodes[i]; ++i){
         if(n.childNodes && n.tagName != 'INPUT'){
             cleanUpInputs(n);
         }else if (n.tagName == 'INPUT' && n.type == 'text') {
             n.value = '';
         }
     }
 }

My select_fields function:

function select_familyfields(e)
{
    ...
    var selectionfamille = e.value;

  $.ajax({
            type: "POST",
            url: "/achats/selection",
            data: {_token: CSRF_TOKEN, code_item : selection },
            dataType: "JSON",
            success: function (data) {       $(e).parents('tr').find('.item_fields[]').text(data.natureachat.LibNatureAchat); 
          ...
        }
    });
}

Answer

You are using selectpicker in your code so this plugin creates its own dynamic htmls and assign ids ,data-attribute to them so when you clone your tr they are copy as well that’s why you don’t see option inside newly added dropdown nor they are able to selected.

Instead , one way to make this work is to store cloned tr in some variable where selectpicker is not yet initialize . Then , whenever add_row() function is call simply use that cloned tr to append inside your tbody and then intialize your selectpicker using $("#add_table tbody tr:last select").selectpicker() .

Demo Code :

var cloned = $("#add_table tbody tr:first").clone() //keep clone for later use..
$("select[name*=item_desc]").selectpicker() //intialize your slectpicker
function add_row() {
  $(cloned).find("input").val("") //empty any input..
  $(cloned).find(".writefields").text("") //clear td 
  $("<tr>" + $(cloned).html() + "</tr>").appendTo($("#add_table tbody")) //append to your tbody..
  $("#add_table tbody tr:last select").selectpicker() //intialize newly added selct...
}

function select_fields(e) {
  var selectionfamille = e.value;
  console.log(selectionfamille)

  /* $.ajax({
     type: "POST",
     url: "/achats/selection",
     data: {
       _token: CSRF_TOKEN,
       code_item: selection
     },
     dataType: "JSON",
     success: function(data) {*/
  //just for demo...
  $(e).parents('tr').find('[name="item_fields[]"]').text("abcxyz") //data.natureachat.LibNatureAchat;

  /*}
  });*/
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">
<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>

<table id="add_table">
  <tbody>
    <tr>
      <td>
        <!--remove selectpicker class and id..-->
        <select name="item_desc[]" onchange="select_fields(this)">
          <option> </option>

          <option>1</option>
          <option>2</option>
        </select>
      </td>
      <td class="writefields" name="item_fields[]">Smethings...</td>
      <td><i class="btn far fa-trash-alt" onclick="remove_row(this)">Delete</i></td>
    </tr>
  </tbody>
</table>
<button onclick="add_row()">Add</button>
We are here to answer your question about Add Row dynamically with SelectPicker - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji