chris05
chris05

Reputation: 745

Attach script to element after AJAX call

I am building an ASP.Net Web API application for users to create to-do items. After making a GET request for a list of a user's items, I am trying to attach a particular function when a certain element is clicked.

In the GET request (done in a separate file), the following is appended to the todo-list div found in the main page:

$('<div class="single-todo"> +
  '<div class="td-delete"><div class="delete-todo" title="Delete" data-id="' + id + '" data-username="' + username + '"></div></div>' +
  '<div class="td-title">' + title + '</div>' + 
  '</div>').appendTo('#todo-list');

In the main page, I am trying to attach a function when the delete-todo div is clicked, namely: (this is put in the .ready() function)

$(".delete-todo").on('click', function () {
    var username = $(this).data("username");
    var id = $(this).data("id");
    DeleteTodo(id, username);
});

(Here, DeleteTodo() is a function within a js file). When the delete-todo div is clicked it is never called, and the only possibility is that the delete-todo div doesn't exist at first (it only exists once the AJAX call is done).

How can I attach the function call to be executed after the AJAX call, without the need to make the same function through inline code?

Upvotes: 0

Views: 76

Answers (2)

Jason P
Jason P

Reputation: 27022

For dynamic elements like this, I would recommend event delegation:

$(document).on('click', ".delete-todo", function () {
    //...
});

That will attach the handler to the document and you won't need to worry about binding to new elements.

Upvotes: 1

neel shah
neel shah

Reputation: 2271

Add the function call in the success call back of the ajax call,so whenever the ajax call returns a 200 status the function will be executed

Upvotes: 1

Related Questions