Javascript – Jquery dynamic addition of form fields problem


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…..

Best Solution

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


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.