Reputation: 1488
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
Upvotes: 0
Views: 119
Reputation: 7196
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.
Upvotes: 1