Skip to content

Update form_collections.rst #3157

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Nov 12, 2013
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 12 additions & 10 deletions cookbook/form/form_collections.rst
Original file line number Diff line number Diff line change
Expand Up @@ -358,27 +358,29 @@ will be show next):

.. code-block:: javascript

// Get the ul that holds the collection of tags
var collectionHolder = $('ul.tags');
var $collectionHolder;

// setup an "add a tag" link
var $addTagLink = $('<a href="#" class="add_tag_link">Add a tag</a>');
var $newLinkLi = $('<li></li>').append($addTagLink);

jQuery(document).ready(function() {
// Get the ul that holds the collection of tags
$collectionHolder = $('ul.tags');

// add the "add a tag" anchor and li to the tags ul
collectionHolder.append($newLinkLi);
$collectionHolder.append($newLinkLi);

// count the current form inputs we have (e.g. 2), use that as the new
// index when inserting a new item (e.g. 2)
collectionHolder.data('index', collectionHolder.find(':input').length);
$collectionHolder.data('index', $collectionHolder.find(':input').length);

$addTagLink.on('click', function(e) {
// prevent the link from creating a "#" on the URL
e.preventDefault();

// add a new tag form (see next code block)
addTagForm(collectionHolder, $newLinkLi);
addTagForm($collectionHolder, $newLinkLi);
});
});

Expand All @@ -393,22 +395,22 @@ one example:

.. code-block:: javascript

function addTagForm(collectionHolder, $newLinkLi) {
function addTagForm($collectionHolder, $newLinkLi) {
// Get the data-prototype explained earlier
var prototype = collectionHolder.data('prototype');
var prototype = $collectionHolder.data('prototype');

// get the new index
var index = collectionHolder.data('index');
var index = $collectionHolder.data('index');

// Replace '$$name$$' in the prototype's HTML to
// instead be a number based on how many items we have
var newForm = prototype.replace(/\$\$name\$\$/g, index);

// increase the index with one for the next item
collectionHolder.data('index', index + 1);
$collectionHolder.data('index', index + 1);

// Display the form in the page in an li, before the "Add a tag" link li
var $newFormLi = $('<li></li>').append(newForm);
var $newFormLi = $('<li></li>').append($newForm);
$newLinkLi.before($newFormLi);
}

Expand Down