Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Shahidhsalarzai's avatar

Cloning a table row with drop down but drop down is not working in second row

i cloned a row through javascript but the drop down in the text area is not working in second row. and options get twice when i add new row. i se text area becouse i need to enter multiple line in text area. you can chek the code with w3 editor

https://www.w3schools.com/tryit/tryit.asp?filename=tryhtml_hello

the code is.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
</head>
<style>
#option-list {
  position: absolute;
  z-index: 2;
  background-color: lightblue;
  border: 1px solid gray;
  max-height: 200px;
  overflow-y: auto;
  display: none;
  border-radius: 4px;
}

#option-list ul {
  margin: 0;
  padding: 0;
  list-style: none;
}

#option-list li {
  padding: 5px;
  cursor: pointer;
}

</style>
<body>

<div class="row">
            <div class="col-lg-12">
              <table class="table table-bordered" id="">
                <thead>
                  <tr>
                    <th>ITEM DETAILS</th>
                    <th>QUANTITY</th>
                    <th>RATE</th>
                   
                    <th >Action</th>
                  </tr>
                </thead>
                <tbody>
                  <tr id="line_1" class="row1">
                    <td>
                      <div class="form-group">
                        <textarea class="form-control" id="options" type="text"
                          style="padding: 5px; overflow-y: hidden; resize: vertical;" list="options-list"
                          placeholder="Type or select"></textarea>
                        <datalist id="options-list">
                          
                          <option value="name1">
                          <option value="name2">
                          <option value="name3">
                            
                        </datalist>
                        <div id="option-list">
                          <ul></ul>
                        </div>
                      </div>
                    </td>
                    
                    
                    
                    <td>
                      <div class="form-group">
                        <input type="number" name="quantity" class="form-control" id="quantity" placeholder="Quantity">
                      </div>
                    </td>
                    <td>
                      <div class="form-group">
                        <input type="number" name="rate" class="form-control" id="rate" placeholder="Rate">
                      </div>
                    </td>
                    <td>
                      <div class="form-group">
                        <button type="button" class="remove btn btn-danger btn-sm text-center ">
                          delete
                        </button>
                      </div>
                    </td>
                  </tr>
                </tbody>
              </table>
              <a id="cloneButton" class="btn btn-primary">Add Item</a>
            </div>
          </div>
          
          
          
          
<script>
 var template = $('#line_1').clone();
$('#cloneButton').click(function () {
    var rowId = $('.row1').length + 1;
    // console.log(rowId);
    var klon = template.clone();   
    // console.log(klon)       
    klon.attr('id', 'line_' + rowId)
        .insertAfter($('.row1').last())
        .find('option')
        .each(function () {
            // $(this).attr('id', $(this).attr('id').replace(/(\d*)$/, ""+rowId));
        })    

        // $("#line_" + rowId).append("<a href='javascript:void(0);' class='remove'>delete</a> ")               
});

$(document).on("click", ".remove", function() {
  if($('.row1').length>1)
  $(this).closest(".row1").remove();
});

  var optionsTextarea = document.getElementById("options");
      var optionList = document.getElementById("option-list");
  
      optionsTextarea.addEventListener("input", function() {
        var searchText = optionsTextarea.value.toLowerCase();
        var matchingOptions = document.querySelectorAll("#options-list option[value*='" + searchText + "']");
        renderOptions(matchingOptions);
      });

      function renderOptions(options) {
        var optionListUl = document.createElement("ul");
        options.forEach(function(option) {
          var optionListLi = document.createElement("li");
          optionListLi.innerText = option.value;
          optionListLi.addEventListener("click", function() {
            selectOption(optionListLi);
          });
          optionListUl.appendChild(optionListLi);
        });
        optionList.innerHTML = "";
        optionList.appendChild(optionListUl);
        optionList.style.display = options.length > 0 ? "block" : "none";
      }

      function selectOption(option) {
        var optionsTextarea = document.getElementById("options");
        optionsTextarea.value = option.innerText;
        optionList.style.display = "none";
      }

      document.addEventListener("click", function(event) {
        if (!optionsTextarea.contains(event.target) && !optionList.contains(event.target)) {
          optionList.style.display = "none";
        }
      });

      optionsTextarea.addEventListener("click", function() {
        var matchingOptions = document.querySelectorAll("#options-list option");
        renderOptions(matchingOptions);
        optionList.style.display = "block";
      });
      // this code for auto expend textarea vertically
      $('#options').on('input', function() {
    this.style.height = 'auto';
    this.style.height = (this.scrollHeight + 2) + 'px';
  });

</script>
          
          
          
</body>
</html>
0 likes
2 replies
LaryAI's avatar
Level 58

The issue is that the cloned row has the same ID as the original row, which causes issues with the dropdown. To fix this, you can update the ID of the cloned row to be unique. Additionally, the options in the dropdown are being duplicated because the option elements are being cloned along with the row. To fix this, you can remove the option elements from the cloned row and add them back in dynamically.

Here's an updated version of the JavaScript code that should fix these issues:

var template = $('#line_1').clone();
$('#cloneButton').click(function () {
    var rowId = $('.row1').length + 1;
    var klon = template.clone();   
    klon.attr('id', 'line_' + rowId)
        .insertAfter($('.row1').last())
        .find('option')
        .remove() // remove options from cloned row
        .end()
        .find('textarea')
        .attr('id', 'options_' + rowId) // update ID of textarea
        .end()
        .find('datalist')
        .attr('id', 'options-list_' + rowId) // update ID of datalist
        .end();

    // add options back to datalist
    var optionsList = klon.find('#options-list_' + rowId);
    optionsList.empty();
    $('#options-list option').each(function() {
        optionsList.append($(this).clone());
    });
});

$(document).on("click", ".remove", function() {
    if($('.row1').length > 1)
        $(this).closest(".row1").remove();
});

Note that this code assumes that the option elements are defined outside of the table, as in the provided code. If they are defined dynamically within the table, you may need to adjust the code accordingly.

Please or to participate in this conversation.