I have a rails app that's using coffeescript. When I refresh the page or go to it directly using the URL, the following code works. When I click a link through to this page and try it out, it doesn't work at all. Why could that be?
jQuery ->
console.log "Ready."
$('form').on 'click', '.add_fields', (event) ->
console.log "Click."
time = new Date().getTime()
regexp = new RegExp($(this).data('id'), 'g')
$(this).before($(this).data('fields').replace(regexp, time))
event.preventDefault()
After a reload, I get Ready and Click when appropriate, and it works. After a click through from another page, I don't get anything. I also get this deprecation warning from chrome, which I'm not sure how to fix since it's coming from within JQuery itself:
event.returnValue is deprecated. Please use the standard event.preventDefault() instead.
jquery.js?body=1:5375
The error only shows up when the code above isn't working. Is chrome blocking it? I'm using jquery-rails (3.0.4)
So it turns out it was turbolinks that was causing the problem. Thanks davidburber for pointing that out. Here's what I did to fix it (from Rails 4: how to use $(document).ready() with turbo-links)
ready = ->
$('form').on 'click', '.remove_fields', (event) ->
$(this).prev('input[type=hidden]').val('1')
$(this).closest('fieldset').hide()
event.preventDefault()
$(document).ready(ready)
$(document).on('page:load', ready)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With