cg22
cg22

Reputation: 355

How do I pass different variables through an onclick function?

What I was doing is this:

$(document).on("click", "#deleteMe", function (){

    var id = $(this).data("id");
    console.log(id);

    // function to delete event by id goes here
});

My delete HTML looks like this:

<div id="deleteMe" data-id="">Delete</div>

A data-id value is given through a different function so that once the page has many events, the data-id field above has numbers like 90, 91, 92, etc. when the modal loads. So, for example:

<div id="deleteMe" data-id="90">Delete</div>
<div id="deleteMe" data-id="91">Delete</div>
<div id="deleteMe" data-id="92">Delete</div>

This works perfectly on the first time that I click 'Delete' - the event is deleted from the database like I want it to. Unfortunately every time I click a DIFFERENT event and click 'delete' again, the delete fails and the console.log says it was trying to delete the previous id of the FIRST element I deleted.

It's like the first time I use the onclick function it binds the original id I used, and every click from then on out keeps the same id instead of passing the new data-id. How do I work around this?

Ex.

Just clicked event 90, hit delete. Event deleted successfully! (Console.log = "Just tried to delete ID #90") Just clicked event 91, hit delete. Nothing happens. (Console.log = "Just tried to delete ID #90"

On inspecting the elements before clicking delete, the correct data-ids are there - it's just on clicking 'delete' that it doesn't grab the new data-id value from the next event I'm trying to delete.

Upvotes: 0

Views: 630

Answers (2)

cg22
cg22

Reputation: 355

I just solved this by changing this function:

var id = $(this).data("id");

to:

var id = $(this).attr("data-id");

I didn't think there was a difference, but double and triple-checking it confirms that these two functions operate differently.

Found some interesting information on it regarding DOM here: http://www.peterbe.com/plog/data-and-attr-in-jquery

Upvotes: 0

jshanley
jshanley

Reputation: 9138

For starter's, if you're going to have multiple elements labeled as deleteMe you should use a class rather than id. ID's should be unique. Perhaps the values you have for data-id should be the id's.

Assuming you changed the elements to:

<div class="deleteMe" data-id="90">Delete</div>

To delete the element that was clicked you could do this:

$('.deleteMe').click(function() {
  console.log('Deleting ID:', $(this).attr('data-id'));
  $(this).remove();
});

--EDIT--

Since folks mentioned that I missed the point of event delegation, you could do it this way to ensure that all future elements created with class deleteMe also respond to the click event:

$(document).on('click', '.deleteMe', function() {
  console.log('Deleting ID:', $(this).attr('data-id'));
  $(this).remove();
});

Upvotes: 1

Related Questions