0

I am dynamically loading three text boxes in a page, I need to take id of text boxes when it is clicked.

$.ajax({
    url: "../taxClass/getTaxClass",
    type: "post",
    contentType: "application/json",
    dataType: "json",
    success: function (data) {
        var taxClassBOs = data.taxClassBOs;
        $.each(taxClassBOs, function (key, value) {
            $("#taxVatId").append('<div><label class="col-sm-3 control-label" for="VatId">' + value.description + '</label></div><div class="col-sm-3"><input type="text" name="vatId" value=""placeholder="' + value.title + '" id="' + value.taxClassId + '" class="form-control" /></div>');
        });
    }
});

I have tried this code

$('input[type="text"]').click(function () {
    var id = $(this).attr('id');
    alert(id);
});
HaveNoDisplayName
  • 8,291
  • 106
  • 37
  • 47
Karthikeyan Raju
  • 109
  • 2
  • 11
  • possible duplicate of [Event binding on dynamically created elements?](http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – Balachandran May 29 '15 at 12:54

3 Answers3

2

You need event delegation to bind the event with dynamically added elements. You can use on() for this.

$('staticParent').on('click','input[type="text"]'function(){

Delegated events

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers.

Adil
  • 146,340
  • 25
  • 209
  • 204
1

Almost correct, but since you are loading them dynamically, you need to delegate

$(document).on('click', 'input[type="text"]',function(){
                         var id = $(this).attr('id');
                         alert(id);
                    });

The reason you need to delegate is because if you attach the handler like

$('input[type="text"]').click(function(){...});

it will attach to only the current elements.

However, with delegation, it will apply the handler to all current and future elements.

AmmarCSE
  • 30,079
  • 5
  • 45
  • 53
0

Use event delegation on dynamically added elements.

$('#taxVatId').on('click', "input[type="text"]", function(){
                         var id = $(this).attr('id');
                         alert(id);
                    });
Zee
  • 8,420
  • 5
  • 36
  • 58