@@ -369,6 +369,10 @@ will be show next):
369
369
// add the "add a tag" anchor and li to the tags ul
370
370
collectionHolder .append ($newLinkLi);
371
371
372
+ // count the current form inputs we have (e.g. 2), use that as the new
373
+ // index when inserting a new item (e.g. 2)
374
+ collectionHolder .data (' index' , collectionHolder .find (' :input' ).length );
375
+
372
376
$addTagLink .on (' click' , function (e ) {
373
377
// prevent the link from creating a "#" on the URL
374
378
e .preventDefault ();
@@ -391,21 +395,24 @@ one example:
391
395
392
396
function addTagForm (collectionHolder , $newLinkLi ) {
393
397
// Get the data-prototype explained earlier
394
- var prototype = collectionHolder .attr ( ' data- prototype' );
398
+ var prototype = collectionHolder .data ( ' prototype' );
395
399
396
- // count the current form inputs we have (e.g. 2), use that as the new index (e.g. 2)
397
- var newIndex = collectionHolder .find ( ' :input ' ). length ;
400
+ // get the new index
401
+ var index = collectionHolder .data ( ' index ' ) ;
398
402
399
403
// Replace '$$name$$' in the prototype's HTML to
400
404
// instead be a number based on how many items we have
401
- var newForm = prototype .replace (/ \$\$ name\$\$ / g , newIndex);
405
+ var newForm = prototype .replace (/ \$\$ name\$\$ / g , index);
406
+
407
+ // increase the index with one for the next item
408
+ collectionHolder .data (' index' , index + 1 );
402
409
403
410
// Display the form in the page in an li, before the "Add a tag" link li
404
411
var $newFormLi = $ (' <li></li>' ).append (newForm);
405
412
$newLinkLi .before ($newFormLi);
406
413
}
407
414
408
- .. note:
415
+ .. note ::
409
416
410
417
It is better to separate your javascript in real JavaScript files than
411
418
to write it inside the HTML as is done here.
0 commit comments