Join the Stack Overflow Community
Stack Overflow is a community of 6.5 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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.

share|improve this question
up vote 3 down vote accepted

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

var js_array =  <%= @qs.to_json %>;
share|improve this answer

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.

share|improve this answer
    
I wanna why give me a minus, I have test my code and works like what you want. – Zoker Jun 30 '15 at 5:39
1  
It gives SyntaxError: illegal character. At var js_array = #{@qs}; – jon snow Jun 30 '15 at 5:50
    
@jonsnow i have updated my answer, but it's really works fine for me ... :( – Zoker Jun 30 '15 at 5:57
1  
Looks like you are using Haml, but the OP uses the ERB template language. So your answer does not answer his question. – spickermann Jun 30 '15 at 6:23
    
@Zoker Its working as haml. (y). Specify that. – jon snow Jun 30 '15 at 6:33

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]
share|improve this answer
    
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 – Cyril Duchon-Doris Mar 6 '16 at 18:30

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.