Search code examples
ruby-on-railscocoon-gem

how to hide remove link when there is only one row/item in the form using link_to_remove_association in rails


I am using cocoon gem to add/remove a record 'on the fly' from a form in rails. Is there a way to hide the remove link which is added on the page using link_to_remove_association if there is only one row/item ?


Solution

  • I fixed it. As the rows were being added from JS, controlling the hiding/showing of the remove link had to be handled from JS itself and not rails.

    $(document).ready(function() {
        $('#container')
          .on('cocoon:after-insert', function() {
            if($(".fields-row").length > 1){
              $(".remove_fields")[0].style.display="block";
            }else{
              $(".remove_fields")[0].style.display="none";
            }
          })
          .on("cocoon:after-remove", function() {
            if($(".fields-row").length == 1){
              $(".remove_fields")[0].style.display="none";
            }else{
              $(".remove_fields")[0].style.display="block";
            }
          });
    });
    

    .remove_fields class is added to the <a> tag automatically when using link_to_remove_association

    For some reason .show()/.hide() methods of JQuery were not working, that is why I have used .style.display