citraL
citraL

Reputation: 1156

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 !

Upvotes: 5

Views: 8403

Answers (2)

AnkitG
AnkitG

Reputation: 6568

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!

Upvotes: 2

ronalchn
ronalchn

Reputation: 12335

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.

Upvotes: 9

Related Questions