Kien Pham Kien Pham - 7 months ago 35
jQuery Question

How to add new form fields using jQuery and $form helper?

I'm trying to let a user to do a 'Click here to add more info' link. I'm trying to do this with input fields so that the id of the field have to increment.

I would like for jQuery to add this on every click where $i is the number of each field incremented:

<div id="info"></div>
<?php echo $form->input("User.$i.first_name"); ?>
<a href = 'add/' id='addInfo'>Add info</a>

Here is my jQuery code so far:

var current = 1;
var newField = '<h4>Info#' + current + '</h4>';
return false;

One of the solution I came up with is just manually create the input fields inside the javascript and assign it to the newField. I think there should be a way where I can create a first working set and then use jQuery to copy that first content and then just increment the count for new fields.



The idea is to count all existing fields and cache that number.

currentFields = $('#yourFormname input').size(); // caches

Now you append another text field and assign it a name based on that field count you had calculated above.

    $('#info').append('<input type="text" name="data[User]['+currentFields+'][first_name]"');
    return false;


Finally, instead of appending fields as strings, you could clone() a field html and then just replace its name attribute with newly calculated.