5

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 !

2 Answers 2

9

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Many thanks! .. I'm a beginner in jQuery, and your answer will help me a lot !
Only in ruby 1.9.x, when you say <%= ... %>, it calls to_s automatically. In ruby 1.9.x, we see [2,3].to_s # => "[2, 3]", but in ruby 1.8.7, [2,3].to_s # => "23" (ie. it outputs "23")
ok thanks for the explanation, I liked your answer, and the Gon gem looks cool also :-)
2

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.