Reputation: 153
I would like to clone table tr and add new btn
into td
with class "rooms_btns".
How can I do that?
$(".add_room_btn").on('click', function() {
new_row_content = $("#clone_row").clone();
new_row_content.removeAttr('id');
new_row_content.append().append("<a href='#'><i class='fa fa-minus-circle fa-2x text-danger'></i></a>").insertAfter("#clone_row");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" />
<table>
<tr id="clone_row">
<td>
<select name="" class="form-control">
<option value="">STANDART</option>
</select>
</td>
<td class="rooms_btns">
<a href="#">
<i class="fa fa-plus-circle fa-2x text-success add_room_btn"></i>
</a>
</td>
</tr>
</table>
Upvotes: 1
Views: 41
Reputation: 67525
You need to append the cloned tr to the table :
$('table').append(new_row_content);
NOTE:
Remove the extra append in :
new_row_content.append().append("<a href='#' class='remove_room_btn'><i class='fa fa-minus-circle fa-2x text-danger'></i></a>").insertAfter("#clone_row");
_______________^^^^^^^^^
Should be :
new_row_content.append("<a href='#' class='remove_room_btn'><i class='fa fa-minus-circle fa-2x text-danger'></i></a>").insertAfter("#clone_row");
Upvotes: 1
Reputation: 337626
To append to the .rooms_btns
cell within the cloned row you need to first select it before calling append()
. To do this you can use find()
:
$(".add_room_btn").on('click', function() {
var $new_row_content = $("#clone_row").clone();
$new_row_content.removeAttr('id');
$new_row_content.find('td.rooms_btns').append("<a href='#'><i class='fa fa-minus-circle fa-2x text-danger'></i></a>");
$new_row_content.insertAfter("#clone_row");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" />
<table>
<tr id="clone_row">
<td>
<select name="" class="form-control">
<option value="">STANDART</option>
</select>
</td>
<td class="rooms_btns">
<a href="#"><i class="fa fa-plus-circle fa-2x text-success add_room_btn"></i></a>
</td>
</tr>
</table>
Upvotes: 1
Reputation: 2768
Try to change jquery to this.
$(".add_room_btn").on('click', function() {
new_row_content = $("#clone_row").clone();
new_row_content.removeAttr('id');
new_row_content.find('.rooms_btns').append("<a href='#'><i class='fa fa-minus-circle fa-2x text-danger'></i></a>");
new_row_content.insertAfter("#clone_row");
});
you could then change your click handler to this
$(document).on('click', ".add_room_btn", function() {
so that all the dynamically added + buttons will work.
Upvotes: 1