4

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?

Nicolas de Fontenay
  • 2,170
  • 5
  • 26
  • 51

4 Answers4

5

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.

Andrew Cooper
  • 32,176
  • 5
  • 81
  • 116
  • As explained in this document, live() doest not work with some events. Changing to 'click' instead fixed it. (almost the same event) I choose this answer as a solution because it was there first and I do need to get the currentId for later use. Thanks everyone for your help. You've set me in the right track. – Nicolas de Fontenay May 24 '11 at 09:34
3

The previous answers are no longer appropriate. They rely on jQuery.live, which is now deprecated. In jQuery 1.11, a call to jQuery.live produces an error. The current preferred solution is to use jQuery.on . The implementation of the jQuery.live code, above, would be as follows. The second parameter, currently set to ":input", can be replaced by a selector that conforms to your needs.

$( "body" ).on('focus', ":input", function() {
    var currentId = $(this).attr('id');
    $("#"+currentId).val('blah');
});
Dale K
  • 25,246
  • 15
  • 42
  • 71
bittids
  • 140
  • 2
  • 5
1

It can be simpler (no need to get id and search by it):

$(document).ready(function() {
    $('input').live('focus', function() {
        $(this).val('blah');
    });
});
bjornd
  • 22,397
  • 4
  • 57
  • 73
0

I belive you are using $("<someid>").focus(<function>). This works on document already loaded and not on new tags added.

Try using $("<someid>").live("focus", <function>);

Also do have a look at jquery website. They got quite nice documentation with examples. For live check this out http://api.jquery.com/live/

Mayank
  • 5,454
  • 9
  • 37
  • 60