I have created a jQuery code that includes 3 pre-existing rows with a text box to add more similar rows. The jQuery functions are initially applied to the first 3 hard-coded rows. I am looking to extend this functionality to dynamically added rows later on. How can I achieve this? Here is the code snippet:
$('input[type="checkbox"]').click(function() {
$(this).next('label').toggleClass('checked', '');
});
$('.glyphicon.glyphicon-trash').click(function() {
$(this).closest("tr").remove();
});
var i = 4;
$("input[type='text']").keypress(function(event) {
if (event.which === 13) {
var Text = $(this).val();
$(this).val("");
var j = "checkbox" + i;
$("tbody").append("<tr><td><div class='checkbox'><input type='checkbox' id='" + j + "'/><label> " + Text + "</label><label class='glyphicon glyphicon-trash' id='" + i + "'></label></div></td></tr>");
i = i + 1;
}
});
.checked {
text-decoration: line-through;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="container">
<table class="table">
<thead>
<tr>
<th>To Do List</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<div class="checkbox">
<input type="checkbox" id="checkbox1" /><label>Task 1</label><label class="glyphicon glyphicon-trash"></label>
</div>
</td>
</tr>
<tr>
<td>
<div class="checkbox">
<input type="checkbox" id="checkbox2" /><label>Task 2</label><label class="glyphicon glyphicon-trash"></label>
</div>
</td>
</tr>
<tr>
<td>
<div class="checkbox">
<input type="checkbox" id="checkbox3" /><label>Task 3</label><label class="glyphicon glyphicon-trash" id="3"></label>
</div>
</td>
</tr>
</tbody>
</table>
<div class="row">
<input type="text" placeholder="Add New Todo">
</div>
</div>