Skip to content
Advertisement

dropdown select not being part upon the process of cloning

Cloning code works it’s just that the dropdown select is not being part of the cloning process.

$("input.tr_clone_add").live('click', function() {
  var $tr = $(this).closest('.tr_clone');
  var $clone = $tr.clone();
  $clone.find('.form-control js-example-basic-single').val('');
  $tr.after($clone);
});
<table>
  <tr class="tr_clone">
    <td>
      <input type="button" name="add" value="clone row" class="tr_clone_add" /><br><br>
      <select name="animal" id="number">
        <option value="cow">cow</option>
        <option value="horse">horse</option>
        <option value="dog">dog</option>
        <option value="cat">cat</option>
      </select>
      &nbsp;
      <select name="vehicle" id="letter">
        <option value="car">car</option>
        <option value="ship">ship</option>
        <option value="plane">plane</option>
      </select>
      &nbsp;
      <input name="remarks" type="text">
      <br>
      <hr>
    </td>
  </tr>
</table>
</body>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>

What I am trying to do is, also pass the value of dropdown select of row to be cloned upon the process of cloning the row.

Advertisement

Answer

  1. live is deprecated so update your jQuery library.

  2. For your question:

    1. First of all find and get selected option and add attribute selected to selected option.

    2. To get events of dynamic created elements , use event delegation.

Example:

$(document).on("change", "select", function() {
  var val = $(this).val(); 
  $("option", this).removeAttr("selected").filter(function() {
    return $(this).attr("value") == val;
  }).first().attr("selected", "selected");
});
$('body').on('click', 'input.tr_clone_add', function() {
  var $tr = $(this).closest('.tr_clone');
  var $clone = $tr.clone();
  $clone.find('.form-control js-example-basic-single').val('');
  $tr.after($clone);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr class="tr_clone">
    <td>
      <input type="button" name="add" value="clone row" class="tr_clone_add" /><br><br>
      <select name="animal" id="number">
        <option value="cow">cow</option>
        <option value="horse">horse</option>
        <option value="dog">dog</option>
        <option value="cat">cat</option>
      </select>
      &nbsp;
      <select name="vehicle" id="letter">
        <option value="car">car</option>
        <option value="ship">ship</option>
        <option value="plane">plane</option>
      </select>
      &nbsp;
      <input name="remarks" type="text">
      <br>
      <hr>
    </td>
  </tr>
</table>
</body>
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement