Question

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.

No correct solution

OTHER TIPS

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
})
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top