简体   繁体   中英

jQuery $(“.class”).click(); - multiple elements, event triggers on all of them

I am working on a TODO app and I am having issues with the event listeners triggering on all of the elements with the same class.

Here is what I have so far:

  • "Add New Card" btn on page load, when the user clicks a dynamically generated list gets appended to the page.
  • The list is wrapped in <div> , containing input and "Add" btn to dynamically add list items to the list.

Roadblock:

  • When the user click on the "Add" btn from the dynamically generated list, it adds list items to all lists.

What I've tried:

  • I found solutions for triggering the 'click' on the "Add" btn only on the e.target . This doesn't work in my situation as I am not clicking on the element that needs to be added, I am clicking on the button that should add the content from the input field.
  • I tried this inside the function configuring the 'click' but it was unsuccessful.
 e.stopPropagation();
 e.stopImmediatePropagation();

I have created a codepen here where you can run the existing code: https://codepen.io/skarmen/pen/qBZYZJQ

I would appreciate any guidance and help here.

Thank you!

1 - Save the button add you clicked:

const add=$(e.target);

2 - pass it into addTask function along side input

 addTask(userInput, add)

3 - Now use that button to find first list. So inf parent form, then immediately following sibling ol

$(add).parent().next("ol").append(

4 - You are generating same ids when you generate taskCardContainer that wont work, use classes: id="to-do-list" and id="clear-btn" needs to be: class="to-do-list" and class="clear-btn" , ids needs to be unique

 $(document).ready(function(event) { /* SUBMIT FUNCTION - listen to a click event on submit & prevent the default behaviour of the submit event - validate the userInput and add it to the list by calling (addTask f) */ function configureSubmitBehaviour() { $('.add-new-task-btn').on('click', function(e) { e.preventDefault() const add=$(e.target); const $eventTargetPreviousEl = $(e.target).prev() // e target = btn, so we are looking for the input field before the add task btn //console.log('e target:', e.target, 'this:', $(this)) //console.log('evenTargetPreviousEl:', $eventTargetPreviousEl) // store userInput in a variable let userInput = $($eventTargetPreviousEl).val().trim() //console.log('userInput:', userInput) // check if the input is valid if (userInput !== '') { addTask(userInput, add) } else { alert('Input cannot be empty. Please enter a valid task.') } }) } /* ADD NEW CARD FUNCTION */ function configureAddCardBehaviour() { $('#add-new-card-btn').on('click', function(e) { e.preventDefault() // append the task card container on btn click addCard() configureSubmitBehaviour() }) } function addCard() { let $taskCardContainer = $(` <div class="task-card-container"> <h2 class="editable"></h2> <!-- Input New Task --> <form> <label for="new-task" class="sr-only">New Task</label> <input class="new-task" type="text" placeholder="New Task" name="new-task"/> <button type="submit" class="btn add-new-task-btn">Add</button> </form> <!-- Task List --> <ol class="to-do-list" class="to-do-list sortable"> <!-- To do items added dynamically here --> </ol> <button class="clear-btn" class="btn clear-list-btn">Clear</button> </div> <!-- Task Board Container ENDS --> `) $('.main').append($taskCardContainer) //console.log('addList works') } /* ADD TASK FUNCTION - add the user input to the list - clear the input field - function is called upon submit */ function addTask(userInput, add) { let removeItem = '<button id="remove">x</button>' let checkbox = '<input type="checkbox">' // append the added element from the list $(add).parent().next("ol").append(`<li>${checkbox} <span data-id="editable-list-item">${userInput}</span> ${removeItem}</li>`); $('.new-task').val('') } configureAddCardBehaviour() })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src='https://cdnjs.cloudflare.com/ajax/libs/jeditable.js/2.0.17/jquery.jeditable.min.js'></script> <!-- jQuery UI --> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <div class="wrapper"> <div class="main"> <h2>Goals List</h2> <p><em>App description and instructions go here</em></p> <button type="submit" id="add-new-card-btn" class="btn">Add New Task Card</button> </div> <!-- Main Container ENDS --> </div> <!-- Wrapper ENDS -->

EDIT:

Just noticed. You are doing something wrong from start, you have a loop somewhere. All this functions call each other with click events inside them is messed up.

Now when you have multiple cards, when adding item to list that is not the last one, it will add a list in right place but also loop all next inputs and issue an alert if empty. Pretty sure this is not intentional.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM