On 5/15/2010 6:45 PM, Brandon Jake12jake wrote:
> So I'm very new to both ruby and javascript, but the basic problem is. I
> have a ruby array @events_this_month, and i'm running a javascript loop
> that basically needs the information from this array. The problem is I
> can't seem to set the proper index for my ruby array. What I have looks
> like this:
>
>
>   for( var i = 0; i < 3; i++)
>   {
>        var title = '<%= @events_this_month[i].title %>';
>     alert(title);
>   }
>
> I've also tried:
>
>         <%= $j = 0 %>
>   for( var i = 0; i < 3; i++)
>   {
>        var title = '<%= @events_this_month[$j].title %>';
>     alert('<%= $j %>');
>                 <%= $j = $j +1 %>
>   }
>
> Any suggestions on how I can access the correct index in my ruby array
> during the javascript loop?
>   

First off, since you didn't specify anything I'll assume your using Rails.

What I'd suggest is first turning your Ruby array into a java-script
array.  Rails adds an easy method to do this: to_json.
If your not using rails you can get the same method with the 'json' or
'json_pure' gems.

This is what I came up with in a quick and dirty test:

<html>
    <script type="text/javascript">
        var arr=<%= [1,2,3, :foo, 'bar'].to_json %>;
        for (var i=0;i<arr.length;i+=1)
            alert(arr[i]);
    </script>
</html>

Note: this is a Ruby list, not a Rails list.  The more appropriate place
for Rails would be the list at:
http://groups.google.com/group/rubyonrails-talk