How to get element id from dynamically generated form elements using jquery?

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

I got a form with some text input shown from the very beginning. When I click on a field, I want to write 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 fine with initial fields, but stops working with fields added via ajax calls.

The trick is that users can click on any field, and I don’t know what they click to. My identifiers are as follows:

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

(the [n] part is also used to organize fields in a form, because the elements are grouped by experience, learning skills, etc.

how can i achieve this

+3
source share
4

:

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

.focus , . .live() , DOM.

+5

. jQuery.live, . jQuery 1.11 jQuery.live . jQuery.on. jQuery.live, , . , ": input", , .

$( "body" ).on('focus', ":input", function() {
    var currentId = $(this).attr('id');
    $("#"+currentId).val('blah');
});
+2

( ):

$(document).ready(function() {
    $('input').live('focus', function() {
        $(this).val('blah');
    });
});
+1

, $("<someid>").focus(<function>). , .

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

Also look at the jquery site. They have good documentation with examples. For a living check this out http://api.jquery.com/live/

0
source

All Articles