Skip to content
This repository has been archived by the owner on Dec 12, 2021. It is now read-only.

How To: Limit max count of nested fields

lest edited this page Aug 15, 2012 · 4 revisions

This script hides or show 'Add new' link depending on how many nested fields are on a page (assuming there is only one nested model).

$(function() {
  var fieldsCount,
      maxFieldsCount = 5,
      $addLink = $('a.add_nested_fields');
  
  function toggleAddLink() {
    $addLink.toggle(fieldsCount <= maxFieldsCount)
  }

  $(document).on('nested:fieldAdded', function() {
    fieldsCount += 1;
    toggleAddLink();
  });

  $(document).on('nested:fieldRemoved', function() {
    fieldsCount -= 1;
    toggleAddLink();
  });  

  // count existing nested fields after page was loaded
  fieldsCount = $('form .fields').length;
  toggleAddLink();
})