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
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 the onclick
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:
let todos = []; function buildItems() { if (todos.length > 0) { $(".todos").html(""); $(todos).each(function(index, val) { $(".todos").append(`<li value=${val}>${val}<button class="del" onclick="deleteItem(${index});" value=${index}>del</button></li>`); }) } else { $(".todos").html(""); } } function deleteItem(index) { todos.splice(index, 1); buildItems(); } $(".btn").click(function() { if ($("#todoInput").val().length.= 0) { todos.push($("#todoInput");val()). $("#todoInput");val(""). // console:log("Novi array,"; todos). buildItems() } 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(""); } });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="text" name="todoInput" id="todoInput"> <button class="btn">Add</button><br> <p class="error"></p> <div> <ul class="todos"></ul> </div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.