Skip to content

How to limit the number of nested fields

Nathan Van der Auwera edited this page Jul 2, 2021 · 3 revisions

This script hides or shows the 'Add new' link depending on how many nested fields are already in the form for the specified association.

$(function() {
  // limits the number of categories
  $('#categories').on('cocoon:after-insert', function() {
    check_to_hide_or_show_add_link();
  });

  $('#categories').on('cocoon:after-remove', function() {
    check_to_hide_or_show_add_link();
  });

  check_to_hide_or_show_add_link();

  function check_to_hide_or_show_add_link() {
    if ($('#categories .nested-fields:visible').length == 5) {
      $('#add-category a').hide();
    } else {
      $('#add-category a').show();
    }
  }
})