-2

in my page I have an add button to add a new field into a table:

$("#add").click(function () {
 var rowCount = $('#scale tr').length + 1;
 var newRow = '<tr id="row' + rowCount + '"><td>IP:</td><td> 
              <input type="text" **class="ip"** id="ip' + rowCount + '" name="ip' + rowCount + '"> </input></td><td>Name:</td><td>  <input type="text" id="n' + rowCount + '" name="n' + rowCount + '"> </input></td><td id="ip' + rowCount + 'ave"></td><td id="add"></td><td></td></tr>';
 console.log(newRow);
 $("#scale  tr:last").after(newRow);
});

The row is added beautifully.

I also have the following function in document ready:

$(".ip").focusout(function(){
    alert("here");
    var id =this.id;
    console.log(id);
    if(!ipcheck(id)){
        console.log("after function");
        $("#"+id).css("color","red");   
    }
    else(pinging(id));
});

This code alerts me whenever I go to the first row of the table (the one which was initially existed) however for the new rows it doesn't work. My idea is to wrap all the listeners in a function and run the function whenever anything changes however as I have a lot of such a thing in my code I was wondering if there is a better/easier way to do it.

kousha
  • 752
  • 2
  • 10
  • 23

1 Answers1

1

Since your input have been added dynamically to the page, all the events will not be available to this element, in this case you need to apply event delegation in order to attach those events to this newly added input elements:

$("#scale  tr:last").on("focusout",".ip",function() {
     // Your code here
})
Felix
  • 37,892
  • 8
  • 43
  • 55
  • You have the right idea here, but you can't delegate from the dynamically-created element (the new row). You must use an element that's available on DOM.ready. – isherwood May 16 '14 at 01:36
  • OP is using `$("#scale tr:last").after(newRow);` so I think `$("#scale tr:last")` is a static parent. – Felix May 16 '14 at 01:38
  • Could be. I'm too tired to be sure. :-) – isherwood May 16 '14 at 01:38
  • It didn't work for me. I just created a new function and added my listeners to it. call that function whenever I add a new row to the table and it is working. – kousha May 16 '14 at 01:49
  • @kou Is `#scale tr:last` also added dynamically? – Felix May 16 '14 at 01:53
  • K so I ended up creating a new function and adding all the listeners to it. Every time I create a new element I call the function. This worked – kousha Jun 20 '14 at 17:55