Skip to content
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

preventDefault does not stop action #595

Closed
randikabanura opened this issue Sep 7, 2020 · 6 comments
Closed

preventDefault does not stop action #595

randikabanura opened this issue Sep 7, 2020 · 6 comments

Comments

@randikabanura
Copy link

I have the following code:

$(document).on('cocoon:before-remove', function (event, insertedItem) {
     if ($('.nested-fields').length <= 1) {
           event.preventDefault();
       }
 });

If only one .nested-fields section is on the DOM, it should prevent the removal.
The code runs and reaches event.preventDefault() and execute it. But the the last .nested-fields section get removed.

Also I have following in the Gemfile:

gem 'cocoon', git: 'https://github.com/nathanvda/cocoon'

Ruby version: 2.7.1
Rails version: 6.0.3.2
Cocoon version: 1.2.14

@nathanvda
Copy link
Owner

Just to rule out the obvious (since you provide no view code, I have to guess), some questions/tests:

  • are you sure the $('.nested-fields') gives the wanted result (you are counting over the complete page?)

So, if you write your code without the test, something like

$(document).on('cocoon:before-remove', function (event, insertedItem) {
     console.log("prevent the deletion!");
     event.preventDefault();
 });

That should block the deletion as expected and add a line in the javascript console: does that work?

@randikabanura
Copy link
Author

I also removed the if block and check the result. But still the sections getting removed. Also console printing the sentence above as well.

@nathanvda
Copy link
Owner

Ah, you are using rails 6, how did you include the javascript-code? For now there is still no "official" way, and maybe some of the libraries available on npm did not support all original features?

@randikabanura
Copy link
Author

randikabanura commented Sep 8, 2020

require("cocoon")

#555 (comment)
I have put this on the application.js. All other features work such as html_options and render_options for add association links.

@randikabanura
Copy link
Author

randikabanura commented Sep 8, 2020

Found the solution. #555 (comment) is working fine. Thanks

@nathanvda
Copy link
Owner

Great you got it working. Nice. 👍 👍

Also I was myself also busy getting it to work in a rails 6 project, so I just released the js on npm, so now you also could just do something like

 yarn add @nathanvda/cocoon 

and then add require("@nathanvda/cocoon") in app/javascript/packs/application.js

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants