I have a simple html table that starts off with two rows. Each row contains 2 form fields. User's can add additional rows to the table as follows:
$('a#addRow').click(function() {
$('#jTable tr:last').after('<tr>'+
'<td><input type="text" name="foo[]" value="" id="foo[]" /></td>'+
'<td><input type="text" name="bar[]" value="" id="bar[]" /></td></tr>');
return false;
});
This works fine.
However, if there is an error detected after the form is posted, then I need to recreate the table with the correct number of rows. At the moment, after posting, the table defaults back to the two starting rows only.
I decided to do this server side.
Controller:
$data['rows'] = count($_POST('foo'));
View
<?php for ($i = 0; $i < $rows; $i++): ?>
<tr>
<td><input type="text" name="foo[]" value=<?php echo $foo[$i]; ?> id="foo[]" /></td>
<td><input type="text" name="bar[]" value=<?php echo $bar[$i]; ?> id="bar[]" /></td>
</tr>
<?php endfor; ?>
Try to port posting of data from standard html-post to AJAX requests. That will ensure that the site is not reloaded when the form is posted -> your table will stay as it is. See JQuery Submit
On submitting form you can store the number of lines in table.
$('form').submit(function(){
// Cool stuff here
// ...
localStorage.setItem('nbLinesinTable', $('table > tr').length);
// or add input to form
}
The k_wave solution's is also reliable.