-1

Possible Duplicate:
jquery click doesnt work on ajax generated content

The issue is that I need to perform a JQuery on click function to an <a> tag created from an Ajax get. I can't seem to find an answer that works for me.

$("#get_button").click(function (e) {
   $.ajax({
     type: 'GET',
     url: 'http://someurl.com/apikey=1234124124',
     dataType: 'jsonp',
     success: function (data) {
       newRow = "<a id='some_id'>test</a>";
       $("#table_id").append(newRow);
     }
  });
});
$('#some_id').click(function (event) {
    event.preventDefault();
    alert('this will pop up if it worked');
});

Edit for clarification: In my code there are multiple rows added with the id of some_id, I forgot to show that.

Community
  • 1
  • 1
Mike
  • 386
  • 2
  • 4
  • 16

1 Answers1

2

you really need to research these types of questions before asking , if you are using newer jquery (i think 1.6 and above ) it is :

$(document).on("click", '#some_id', function (event) {
    event.preventDefault();
    alert('this will pop up if it worked');
});

older versions use .live() instead of .on()

For the edit in your question - DO NOT have multiple elements with the same id , give them the same class , you can dynamically create ids and add something to each one if you want , like #some_id0 #some_id1 ect...

Scott Selby
  • 9,420
  • 12
  • 57
  • 96
  • It works! but only once for me and only with the first element that has id="some_id", I have multiple items with id="some_id". – Mike Oct 20 '12 at 23:24
  • @Mike that is because you should never have 2 different elements with the same id – Scott Selby Oct 20 '12 at 23:42
  • Then what should I do, the Ajax function is producing a list of items so the user may choose one, or if they change their mind choose a different one. – Mike Oct 20 '12 at 23:51
  • @Mike - like a reccomended , dynamically create elements giving them unique id's with 0, 1, 2, 3 ect. after the id name - or just don't give them an id , just give them a class , then you can access that div in the click even with $(this) – Scott Selby Oct 20 '12 at 23:55