I have a shopping cart, and it once an item is added a trash icon appears. There is a current script that works but it targets all of the 'onclick' functions in the page. I would just like it to target this one (garbage can one). Here is the code for the icon.
<td class="total">
<span class="close" style="color:#f00;">
<i class="fa fa-trash"></i>
</span>
</td>
Now the current JavaScript is like this:
$( document ).ready(function() {
$('body').on('click','.close', function(){
var here = $(this);
var rowid = here.closest('tr').data('rowid');
Theres more JavaScript although I'm just showing the beginning.
I tried something like this, but nothing worked.
$( document ).ready(function() {
var trash = document.getElementsByClassName("fa fa-trash");
trash.on('click', '.close', function(){
var here = $(this);
I don't know if I am on the right track.
Replace
var trash = document.getElementsByClassName("fa fa-trash");
with
var trash = $(".fa.fa-trash");
If you want to use JS
to fetch the elements, using document.getElementsByClassName
then you will have to iterate over a for loop and bind the events specifically for each.
var trashes = document.getElementsByClassName("fa fa-trash");
for(var i=0; i< trashes.length; i++) {
var $trash = trashes[i];
$trash.on('click', '.close', function() {
...
} // end of for loop
Use querySelectorAll
var trash = document.querySelectorAll(".fa.fa-trash");
trash.on('click', ...
If i understand you correctly, you just want to bind the click
event to the trash icons?
If so..
$( document ).ready(function() {
$('body').on('click','.fa.fa-trash', function(){
var here = $(this); //This variable now equals the clicked trash element.
var rowid = here.closest('tr').data('rowid');
Furthermore, it's best practice to use a $
sign on the front of the variable when it contains a jQuery element. That way you and anyone else reading the code can distinguish between the elements and know which variables can have jQuery methods executed upon.
var $here = $(this);