Home > other >  dropdown select not being part upon the process of cloning
dropdown select not being part upon the process of cloning

Time:01-10

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 >
    <td>
      <input type="button" name="add" value="clone row"  /><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.

CodePudding user response:

  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 >
    <td>
      <input type="button" name="add" value="clone row"  /><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>

  • Related