0

If a user is on a form page, I am trying to throw a confirm message if they navigate away without clicking the update button.

The coffeescript code I am using is as follows

# used to detect if a user is navigating off a page
if form_click == true
  window.onbeforeunload = ->
    "You have unsaved data! do you really want to exit?"

If I use if 1 ==1 or 1 ==2 as a test case, it works perfectly fine. However, I am having diffculty in sending a variable from the link_to code to set form_click.

I have tried the following

<%= f.button :button, :class => 'btn-primary',
            data: {form_click: true},
            remote: true %>

But I am not able to pass the variable to the coffeescript code. I am definitely not proficient with javascript and coffeescript, as this probably shows, and would be grateful of any advice on how to resolve this would be much appreciated

1 Answer 1

1

Have a look at the generated HTML. I suspect that the link_to is creating something similar to:

<button class="btn-primary" data-form_click="true" data-remote="true"></button>

If so then the coffeescript you need to have would be something like:

$('data-form_click').click( ->
  if $(this).attr('data-form_click') == 'true'
    window.onbeforeunload = ->
      confirm("You have unsaved data! Do you really want to exit?")
)

The code above is off the cuff, but the main point is that the attribute on the button is a string, not a boolean, so you need to adjust accordingly.

Use the JS debugging tools to place a breakpoint so you can inspect the value of form_click is also another way to see what you should be comparing to.

Sign up to request clarification or add additional context in comments.

2 Comments

Very good catch: "the attribute on the button is a string". As == in CoffeeScript test for both value and type (like === in JavaScript) OP should use the string 'true' not the boolean true. BTW, attr() always returns a string, whereas data() try to cast to some other native type (see stackoverflow.com/questions/25321554/…)
Huh - I've never looked at data() in the jQuery docs. You could reduce the condition to if $(this).data('form_click') - looks much nicer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.