I have this html table:
<table id="sanityTestsTable" border="1">
<tbody>
<tr>
<th>ID</th>
<th>Sanity Check</th>
<th>Result</th>
</tr>
<tr>
<td>1</td>
<td><input name="sanityItem" size="20" maxlength="255" type="text"></td>
<td>Not available yet</td>
</tr>
<tr>
<td>2</td>
<td><input name="sanityItem" size="20" maxlength="255" type="text"></td>
<td>Not available yet</td>
</tr>
</tbody></table>
Whenever the user enters anything in input
field I like to add new empty input
field. This works fine with jQuery:
$("input[name='sanityItem']").change(function(){
var emptyRows = 0;
$("#sanityTestsTable tbody > tr td:nth-child(2) input").each(function(){
if ( $(this).val() == "" )
emptyRows++;
});
if ( emptyRows < 2 ) {
$("#sanityTestsTable tbody > tr").each(function(index){
if ( $(this).is($("#sanityTestsTable tbody > tr:last")) ) {
var txt1 = "<tr><td>" + (index + 1) +"</td><td><input name=\"sanityItem\" size=\"20\" maxlength=\"255\" type=\"text\"></td><td>Not available yet</td></tr>";
$(txt1).insertAfter(this);
var lastRow = $("#sanityTestsTable tbody > tr:last");
// This does not work:
lastRow.on("change", null, lastRow, $("input[name='sanityItem']").change() );
}
});
}
});
Howver the change
event is not caught on new inserted rows. New rows are only added when initial rows 1 or 2 are edited. When you enter text into new row (e.g. 3) then I like further empty rows to appended. What is the proper usage of .on()
call? I also tried with .bind()
but no success either.
After many "try and errors" I got it:
function changeHandler() {
var emptyRows = 0;
$("#sanityTestsTable tbody > tr td:nth-child(2) input").each(function(){ if ( $(this).val() == "" ) emptyRows++; });
if ( emptyRows < 2 ) {
$("#sanityTestsTable tbody > tr").each(function(index){
if ( $(this).is($("#sanityTestsTable tbody > tr:last")) ) {
var txt1 = "<tr><td>" + (index + 1) +"</td><td><input name=\"sanityItem\" size=\"20\" maxlength=\"255\" type=\"text\"></td><td>Not available yet</td></tr>";
$(txt1).insertAfter(this);
// Attach change handler to last row
$("#sanityTestsTable tbody > tr:last td:nth-child(2) input").on("change", function() { changeHandler() });
}
});
}
}
$("input[name='sanityItem']").change( function() {changeHandler()} );