Joy
Joy

Reputation: 4473

Accessing Ruby variable inside a Javascript

I am new to Javascript. I am writing a view in haml that fills a dropdown box by using JQuery and to fill that box JQuery requires the value of a Ruby variable s_id like following:

$(document).ready(function(){
  var param = s_id  //here s_id is a ruby variable
  ...

Here s_id is a ruby variable that is defined in the Haml view file for which the JS get called. Can anyone give any idea how to achieve the above thing.

Upvotes: 2

Views: 2353

Answers (2)

Tim Dorr
Tim Dorr

Reputation: 4921

You'll need to move it to be a partial. Set it up in a file called something like app/views/whatever/_some_script.js.erb and then reference it like so:

render partial: 'whatever/some_script', locals: { s_id: s_id }

In the javascript file, you'll do this:

$(document).ready(function(){
  var param = <%= s_id %>;
  ...

Make sure if it's a string, you put quotes around it. That should be it.

Upvotes: 0

KappaNossi
KappaNossi

Reputation: 2706

I don't think there's a way to directly access the variable. If the JS code is on the same page, you can just add the value using <%= s_id %>. I haven't used HAML much, so you would have to adapt it from this ERB code.

Another solution, since your doing it after document.ready is to store the value in a hidden field and then select it from JS $('#your_sid_field').val()

Upvotes: 2

Related Questions