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>
<select name="vehicle" id="letter">
<option value="car">car</option>
<option value="ship">ship</option>
<option value="plane">plane</option>
</select>
<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:
live
is deprecated so update your jQuery library.For your question:
First of all find and get selected option and add attribute
selected
to selected option.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>
<select name="vehicle" id="letter">
<option value="car">car</option>
<option value="ship">ship</option>
<option value="plane">plane</option>
</select>
<input name="remarks" type="text">
<br>
<hr>
</td>
</tr>
</table>
</body>