Reputation: 75
I am adding items to a list whenever a user pushes as "Add Item" button. When this happens the list item should be added using JQuery. In addition there is another function that will add a delete button for every list item so that the list items may be deleted.
My problem is that every time the "Add Item" button is pressed it triggers the addDeleteButton function such that numerous delete buttons are added. My addDeleteButton gets a JQuery object of all the list items and loops through them. The loop will look for an existing delete button and only add a delete button if there is not currently one there. However I can't seem to find the correct way to write this condition. What can I do to ensure that the a delete button is added only on the condition that there is no previous button?
//gets element with id list so items can be appended to it
let list = $('#list');
//adds a delete button to the li element (only one button added per li)
function addDeleteButton() {
let li = $('li');
let button = '<button>delete</button>';
//this condition should limit the number of buttons added to each li
if (li.children(button) < 1) {
li.append(button);
}
}
//function adds new item to list
function addListItem() {
let li = '<li>' + input.val() + '</li>';
list.append(li);
addDeleteButton();
}
//listens for a click of the "Add" button which triggers list item to be added to list
$('#addLiButton').on('click', addListItem);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form name="list">
<input type="text" name="item" id="input" />
</form>
<div id="addLiButton">Add Item</div>
<ol id="list"></ol>
Upvotes: 0
Views: 573
Reputation: 28522
You can get last li
added using $('li:last')
and then check if the length of button is 0
inside that li
then only add delete button .
Demo Code :
let list = $('#list');
let input = $('#input');
function addDeleteButton() {
let li = $('#list li:last'); //get last li added
let button = '<button>delete</button>';
//then check if the li doesnot has button in it
if (li.find("button").length == 0) {
li.append(button); //add that inside button
}
//or directly append button i.e : li.append(button);
}
function addListItem() {
let li = '<li>' + input.val() + '</li>';
list.append(li);
addDeleteButton();
}
$('#addLiButton').on('click', addListItem);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form name="list">
<input type="text" name="item" id="input" />
</form>
<div id="addLiButton">Add Item</div>
<ol id="list"></ol>
Upvotes: 1