I have a form that has its fields dynamically added as such:
function addFieldRow() {
$('.form-container').append('
<div><input type="text" name="name[1]"></div>
<div>
<select name="choice[1]">
<option value="red">red</option>
// . . .
</select>
</div>
// . . .
');
}
I then pass these to its respective CodeIgniter controller with the declared array form_validation rules:
$this->form_validation->set_rules('name[]', 'text field', 'required');
// . . . other fields' rules
The problem is that if any of the dynamically added forms have an error, these are gone during the view loading. I want to know if how can I preserve the dynamically added form fields after the validation run with errors:
if ($this->form_validation->run() == FALSE) {
// do stuff to preserve the dynamically created fields to show their errors
$this->load->view('user_addresses_view');
}
Better solution
I have found the solution to preserve these dynamically added elements by using ajax
to connect to the form's respective controller in the CodeIgniter framework. This method can:
- Do client-side and server-side validation without refreshing the page
- Since the page does not refresh, all these dynamically added form elements will not disappear!
Solution by james246