views:

1468

answers:

3

I'm using the following code to insert extra form fields.

function addFormField() {
$("#divTxt").append("<div id='education" + id + "'><input name='name' id='name' type='text' size='20'><a href='#' onClick='removeFormField(\"#education" + id + "\"); return false;'><img src='images/minus.gif' width='10px' border=0></img></a></div>");
}

I'm dynamically sending the field values to mysql when a blur event occurs. However, when this field is inserted, it doesn't recognise and the blur event isn't picking up when any value has been entered on the new fields. Is this due to the original blur event handler being set up on document ready?

How do I get the mysql update jquery code to recognise when the extra form fields are made visible after the document ready initialisation has already been completed? I've tried various events based on the div id but to no avail.....

A: 

You should bind your events using the live() method:

for example:

$("input").live("blur", function() { ... });

That way, any fields added at runtime will be bound to the event handler.

EDIT: as pointed out in the comments, "blur" is not supported, but there's a plugin that does support this event: http://plugins.jquery.com/project/livequery

Philippe Leybaert
blur isn't supported by live(): http://docs.jquery.com/Events/live#typefn
Paolo Bergantino
you're right. missed that...
Philippe Leybaert
+2  A: 

The reason your code is not working for the dynamically added inputs is because when you do something like:

$(selector).blur(myFunction);

jQuery goes through every element that matches selector at that point and adds an event handler that runs myFunction when the blur event is fired happens on the element. This means that any elements that match selector added after this line of code runs will not have been bound.

To get around this problem, jQuery introduced the live function in 1.3. As the documentation reads:

Binds a handler to an event (like click) for all current - and future - matched element. Can also bind custom events.

Unfortunately, as of right now jQuery does not support the blur event with the live function.

Your options then are:

A) Run the binding code everytime you add new inputs.
B) Use the livequery plugin, which is that live is based off of and does support blur.

Personally, I would go with A.

Paolo Bergantino
A: 

Thanks for the help - livequery was the ideal solution.

Choog