Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
125
rated 0 times [  132] [ 7]  / answers: 1 / hits: 160768  / 10 Years ago, tue, february 11, 2014, 12:00:00

I have a list view for delete id. I'd like to add a listener to all elements with a particular class and do a confirm alert.



My problem is that this seems to only add the listener to the first element with the class it finds. I tried to use querySelectorAll but it didn't work.



var deleteLink = document.querySelector('.delete');

deleteLink.addEventListener('click', function(event) {
event.preventDefault();

var choice = confirm(sure u want to delete?);
if (choice) {
return true;
}
});


List:



<?php 
while($obj=$result->fetch_object())
{
echo '<li><a class=delete href=removeTruck.php?tid='.$obj->id.'>'.$obj->id.'</a>'
. '<a href=# class=delete></a>
</li>'.n;
}
/* free result set */
$result->close();
$mysqli->close();
?>

More From » javascript

 Answers
129

You should use querySelectorAll. It returns NodeList, however querySelector returns only the first found element:



var deleteLink = document.querySelectorAll('.delete');


Then you would loop:



for (var i = 0; i < deleteLink.length; i++) {
deleteLink[i].addEventListener('click', function(event) {
if (!confirm(sure u want to delete + this.title)) {
event.preventDefault();
}
});
}


Also you should preventDefault only if confirm === false.



It's also worth noting that return false/true is only useful for event handlers bound with onclick = function() {...}. For addEventListening you should use event.preventDefault().



Demo: http://jsfiddle.net/Rc7jL/3/






ES6 version



You can make it a little cleaner (and safer closure-in-loop wise) by using Array.prototype.forEach iteration instead of for-loop:



var deleteLinks = document.querySelectorAll('.delete');

Array.from(deleteLinks).forEach(link => {
link.addEventListener('click', function(event) {
if (!confirm(`sure u want to delete ${this.title}`)) {
event.preventDefault();
}
});
});



Example above uses Array.from and template strings from ES2015 standard.


[#72592] Monday, February 10, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jarod

Total Points: 62
Total Questions: 111
Total Answers: 83

Location: Saint Vincent and the Grenadines
Member since Sat, Sep 11, 2021
3 Years ago
;