yerassyl
yerassyl

Reputation: 3058

CoffeScript works only after page reload in Rails app

I have two selects, the second one changes according to the value of the first one. I use CoffeScript.

		<%= f.collection_select :type, RequestType.order(:typeName), :id, :typeName, 
{include_blank:true }, {:class => "types"} %>
   
 <%= f.grouped_collection_select :subtype, RequestType.order(:typeName), 
:RequestSubTypes, :typeName, :request_type_id, :subTypeName, 
{include_blank:true},
{:class => "subTypes" }  %>
When select 1 changes the options in the second one reloads (options in the second select depend on the option selected in the first. Here is my CoffeScript code:

jQuery ->
	subTypes = $(".subTypes").html()
	$(".subTypes").parent().hide()
	$(".types").change ->
		type = $(".types :selected").text()
		options = $(subTypes).filter("optgroup[label='#{type}']").html()
		if options 	
			$(".subTypes").html(options)
			$(".subTypes").parent().show()
		else
			$(".subTypes").empty()
			$(".subTypes").parent().hide()
It works, but only after I reload the page. If I access page from general link_to it seems that CoffeScript is not working. So when a navigate to that page I alway have to reload the page. The navigation to the page using link_to looks like ajax, but i am not using ajax. Here is my link_to:

<%= link_to "link", new_request_path %>

Upvotes: 1

Views: 84

Answers (1)

Almaron
Almaron

Reputation: 4147

I believe you're using turbolinks. That's way your jquery bootstrap is executed once on the page you initially visit and does not hook up with the DOM of the other pages, hense your callback does not catch up.

You got couple options to deal with it.

  1. Use an attribute data-turbolinks-track='false' on the javascript_tag in your layout head. That way the js file will be loaded and executed on each page load along with the body.

  2. Move the entire javascript_tag call to the bottom of your body.

  3. Use the jquery-turbolinks gem.

Upvotes: 5

Related Questions