简体   繁体   中英

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 !

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.

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM