im trying to make and the same event fire every time but it only fires once when i click "del" button
HTML
<input type="text" name="todoInput" id="todoInput">
<button class="btn">Add</button><br>
<p class="error"></p>
<div>
<ul class="todos"></ul>
</div>
jQuery
var todos = [];
$(".btn").click(function() {
if ($("#todoInput").val().length != 0) {
todos.push($("#todoInput").val());
$("#todoInput").val("");
console.log("Novi array:", todos);
$(".todos").html("");
$(todos).each(function(index, val) {
$(".todos").append(`<li value=${val}>${val}<button class="del" value=${index}>del</button></li>`);
});
**$(".del").click(function() {
todos.splice($(this).val(), 1);
$(".todos").html("");
$(todos).each(function(index, val) {
$(".todos").append(`<li value=${val}>${val}<button class="del" value=${index}>del</button></li>`);
});**
});
} else {
$(".error").text("Molimo unesite vrijednost.");
console.log("Trenutni array:" ,todos);
}
});
$("#todoInput").on("input", function() {
if ($("#todoInput").val().length != 0 && $(".error").text("Molimo unesite vrijednost.")) {
$(".error").text("");
}
});
im trying to make and the same event fire every time but it only fires once when i click "del" button
2
Answers
We actually use on/off click to make sure the click triggers the event.
$(".btn").off (‘click’).on(‘click’,function() {…}
The issie you have is that the
(".del").click(function() {
function is not running repeatedly and therefore not binding theonclick
handler to it.Perhaps an alternative method would be to create the delete function and pass in the the index of the item to delete, see below snippet: