Steve.NayLinAung
Steve.NayLinAung

Reputation: 5155

Rails: How to run javascript when the controller render action

For the sake of argument, we have "new product" form.

I use some javascript libraries for html form elements (e.g. icheck, select2, wysihtml5). These form elements needed to be run with their associated js library functions to show properly (e.g. $(".checkbox").iCheck({...}) ) before rendering the HTML page.

If there is validation errors on submitting the form, Rails will render action "new" to reshow "new product" form with errors (exactly in the "Create" method in "ProductsController").

The problem is Rails will not execute associated javascript files (e.g. products.js.coffee) again in this situation. Then, the javascript based html form elements cannot be shown properly as they should be (because $(".checkbox").iCheck({...}) does not get executed).

How can I resolve this problem?

Upvotes: 0

Views: 641

Answers (1)

jklina
jklina

Reputation: 3417

This could be a turbolinks problem. Look at the jquery-turbolinks gem, or try the following:

ready = ->

  ...your coffeescript goes here...

$(document).ready(ready)
$(document).on('page:load', ready)

You could also try and disable turbolinks to see if it is, in fact, the issue.

Upvotes: 1

Related Questions