GrahamJRoy
GrahamJRoy

Reputation: 1643

Escaping " in Rails and Javascript

I have an array of hashes that consists of my product data in @product_records. I can extract the name of the product using the map function like this:

<%= @product_records.map{|x|x["Name"]} %>

which renders exactly how I want it to the page like this:

["Product1","Product2",...,"Productn"]

I want to try and pass this into a javascript variable so that I can use it with JQuery autocomplete.

var data = <%= @product_records.map{|x|x["Name"]} %>

When I try and set it though the double quotes are escaping like this:

[&quot;Product1&quot;, &quot;Product2&quot;,...,&quot;Productn&quot;]

I have tried various things to try and get the quotes back (.to_json etc) but nothing seems to work. There probably a very simple answer to this but I can't find what it is.

Cheers for any help.

Upvotes: 29

Views: 13819

Answers (3)

F&#225;bio BC Souza
F&#225;bio BC Souza

Reputation: 1220

In my case I had to use like this, for example: <%= j raw @products %>

Upvotes: 1

Rameshwar Vyevhare
Rameshwar Vyevhare

Reputation: 2759

When you use that variable in javascript make sure, you have single quote to execute rails code in javascript.

'<%= raw @products.to_json %>'

thanks

Upvotes: 12

Svilen
Svilen

Reputation: 2648

Use <%= raw your_variable %> :)

Upvotes: 79

Related Questions