views:

67

answers:

3

I'm using jQuery to dynamically add form elements to a web form. Users can "add a time slot" to their request form by clicking a button/link. When clicked, I'm using .after() to add another two rows to the form table, as well as the labels and fields.

The last column in the appended code is a link that says "Remove".

$(document).ready(function() {
    var i=2;
    $("#add_time_slot").click(function() {
     $("#time_slot_table tr:last").after('<tr"><td ... etc ... </tr><tr> ... etc ...<td><a class="removeslot" href="#">Remove</a></td></tr>');
     i++;

     return false;
    });
});

Lots of HTML code in there so I pulled the regular stuff out to keep it clean. There's nothing too strange where the ... etc ... is.

So far, so good. It works great. But then I write this code as the beginnings of what I will use when the "Remove" links are clicked:

$("a.removeslot").click(function() {
 alert("It worked!");
 return false;
});

It won't work. If instead, I put something like $("#header a") in that same code, in place of the $("a.removeslot"), it works fine and when I click on any link in the header, it returns false and runs the alert. But when it's the a.removeslot, it always goes to the "#" URL (doesn't return false) and it never runs the alert.

This seems so basic it's giving me a stomachache. What's wrong with the code??

Thanks.

+5  A: 

You need to use live() if that removeslot link is added dynamically after page load. So, write it like so:

$("a.removeslost").live("click", function() {
  ...
}):

More info: http://docs.jquery.com/Events/live

Bartek
That was it exactly. I'd never heard of .live() -- thanks so much!
Jason Rhodes
A: 

This is because your link is added after the page is loaded and is not there when the event is "assigned", you should use JQuery live events.

Soufiane Hassou
A: 

I'm no jQuery expert, but I think it's because you need to re-apply the event handler after you dynamically add the table rows because jQuery doesn't know about the new rows when you first declare the event handler. I've tried to write an explanation of this on my blog, it might help.

jordelver
Ignore me, sounds like these other guys have a better idea :)
jordelver