2

I am trying to convert a ruby array to javascript array in my rails application

@qs #=> [1, 4]

The javascript code is:

var js_array =  [<%= @qs.to_json %>];
var arrayLength = js_array.length;
for (var i = 0; i < arrayLength; i++) {
    alert(js_array[i]);
}

But I am getting the arrayLength as 1. The alert message in the loop display 1,4 once.

I have tried converting the array to string array, but there is no difference:

var new_array = js_array.map(String);

What I need: I should be able to loop through the javascript array and alert each element.

3 Answers 3

3

The to_json method returns a string that includes the array brackets. Therefore this should work:

var js_array =  <%= @qs.to_json %>;
Sign up to request clarification or add additional context in comments.

Comments

0

Just pass the @qs array to js_array when using Haml template language

var js_array = #{@qs} ;

Code in views:

:javascript
  var js_array =  #{@qs};
  var arrayLength = js_array.length;
  for (var i = 0; i < arrayLength; i++) {
    alert(js_array[i]);
  }

@qs = [1,2] in controller.

4 Comments

I wanna why give me a minus, I have test my code and works like what you want.
It gives SyntaxError: illegal character. At var js_array = #{@qs};
@jonsnow i have updated my answer, but it's really works fine for me ... :(
Looks like you are using Haml, but the OP uses the ERB template language. So your answer does not answer his question.
-1

This works for me...

<script type="text/javascript">
var js_array = <%= @arr %>
var arrayLength = js_array.length;
for (var i = 0; i < arrayLength; i++) {
    alert(js_array[i]);
}
</script>

In my controller

@arr = [1,2,3]

1 Comment

It works because this is a simple case. You can't just dump a Ruby variable in a javascript code without to_json or escape_javascript

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.