How to get element Id from dynamically generated form elements with jquery?

Nicolas de Fontenay picture Nicolas de Fontenay · May 24, 2011 · Viewed 30.7k times · Source

To try the concept, I'm doing a very simple test.

I got a form with some text input showing up from the start. When I click on a field, I want to capture its Id, and add a value to the input text.

$(document).ready(function() {
    $('input').focus(function() {
        var currentId = $(this).attr('id');
       $("#"+currentId).val('blah');
    });
});

This works great with the initial fields, but it stops working with the fields added using ajax calls.

The trick is, users are able to click on any field and I don't know which until they click. My Ids looks like this:

experience0-CompanyName //(original one)
experience[n]-CompanyName

(the [n] part is also used to order the fields in the form as elements are grouped by experience, education skills etc...

how can I achieve this?

Answer

Andrew Cooper picture Andrew Cooper · May 24, 2011

A simple change:

$(document).ready(function() {
    $('input').live("focus", function() {
        var currentId = $(this).attr('id');
       $("#"+currentId).val('blah');
    });
});

.focus only binds to elements that exist at the time it's called. .live() binds a function to an event for all existing elements, and any that are added to the DOM later.