0

Hey guys I have some jquery code that adds a row to a table with a link to remove it and return it back to the select. Here's the code:

$('#addUser').on('click', function (e) {
    var selectedUser = $('#Utilizadores option:selected').text();
    $('#tabela > tbody:last').append('<tr id="'+selectedUser+'"><td>' + selectedUser + '</td><td><a id="removeUser" href="#" class="btn btn-default btn-xs"><i class="glyphicon glyphicon-remove"></i></a></td></tr>');
    $("#Utilizadores option[value='" + selectedUser + "']").remove();
    e.preventDefault();
});

It works! But now I want to do the reverse action of this. So I was just tying it out and not even the alert goes off. Here's the remove code:

$('#removeUser').on('click', function (e) {
    alert('teste');
    e.preventDefault();
});

The same id I gave to the <a> tag but still nothing gets called. I inspect the element and the id is corret and everything.

Does anyone know what the problem is?

João Cunha
  • 9,929
  • 4
  • 40
  • 61
  • 2
    try `$(document).on('click','#removeUser', function() { });` – Brian Dillingham Sep 29 '14 at 16:01
  • 1
    Just like @Brian mentioned, you need delegation here. You can't attach an event handler to an element that's not part of the DOM yet. – emerson.marini Sep 29 '14 at 16:02
  • Thanks guys it worked. If he wants he can make an answer for it so I can approve or something. – João Cunha Sep 29 '14 at 16:04
  • 1
    No accepted answer needed, its a duplicate of [jQuery - Click event doesn't work on dynamically generated elements](http://stackoverflow.com/questions/6658752/jquery-click-event-doesnt-work-on-dynamically-generated-elements) and has been answered well already. – Brian Dillingham Sep 29 '14 at 16:05
  • 1
    If you have multiple `id="removeUser"` on the page, I'd suggest changing them to classes `class="removeUser"`. Despite the fact that Event Delegation will work fine with duplicate IDs, it's still bad practice. – Stryner Sep 29 '14 at 16:07
  • you need delegated event – Ehsan Sajjad Sep 29 '14 at 17:46

2 Answers2

0

To anyone who stumbles here and doesn't see the warning above!

You can check a Question for the same problem here

Community
  • 1
  • 1
João Cunha
  • 9,929
  • 4
  • 40
  • 61
-1

Try using the live() method

$('#removeUser').live('click', function (e) {
    alert('teste');
    e.preventDefault();
});
A.McCoy
  • 19
  • 1
  • 5