Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access rails variables within Javascript code?

I am using Rails 3.0.5

I have a javascript code that uses jQuery dropdown checklist and I would like to have the checkboxes displaying which item is checked already and which is not, when using my form in the 'Edit' action of my belongings controller.

Basically, it can work like this in Javascript:

$('element').val([1,3,4]);
$('element').dropdownchecklist();

Let us say that in my controller, edit action, I have a instance variable called @selected_items that contains the items that are selected (here: @selected_items = [1,3,4]) and I would like to use the value of this instance variables into my Javascript code, how could I proceed ? How could I access the value of this instance variable in a .js file ?

Many thanks for your answer !

like image 759
citraL Avatar asked Sep 04 '12 09:09

citraL


2 Answers

Just write the javascript in your view, and at the appropriate place, print the @selected_items array as json:

app/views/*/*.html.erb

<script>
  $('element').val(<%= @selected_items.to_json %>);
  $('element').dropdownchecklist();
</script>

You can also use the Gon gem if to_json cannot serialize more complicated objects.

like image 192
ronalchn Avatar answered Oct 12 '22 22:10

ronalchn


A better and a clean/neat way of handling such requirements is

1.Don't create javascript inside the views not as per the rails best practices

2.Handle it this way

In your app/views/*/*.html.erb where you are having the instance variable like (@selected_items) assign it into the options within the helpers something like :sel => @selected_items

In your javascript

<script>
  $('element').attr('sel');
  $('element').dropdownchecklist();
</script>

I hope it helps!

like image 28
AnkitG Avatar answered Oct 12 '22 20:10

AnkitG