Values broken converting from rails into javascript

I have a section of javascript which i’m trying to use to dynamically
generate the options for a mult-select box, when another box’s contents
are changed. Basically i have a method that returns an array of arrays,
where each array is of the form

[name, number]

I then iterate over the arrays, and substitute in the values out of the
array -

do |option_tag, i| -%>
$(“subject_family_members[]”).options[<%= i+1.to_i %>]=new Option(’<%=
option_tag[0] %>’, <%= option_tag[1].to_i %>, false, false);
<%end %>

When i run this in the console (escaping the quotes), it seems to
produce the right results -

$(“subject_family_members[]”).options[1]=new Option(“All”, 0, false,
$(“subject_family_members[]”).options[2]=new Option(“Violin”, 13, false,
$(“subject_family_members[]”).options[3]=new Option(“Viola”, 14, false,
$(“subject_family_members[]”).options[4]=new Option(“Cello”, 15, false,
$(“subject_family_members[]”).options[5]=new Option(“Double Bass”, 16,
false, false);

However, when it’s run on the page, all the strings come out as “60” and
all the numbers come out as “111” - i see this javascript when i look at
the page source -

$(“subject_family_members[]”).options[1]=new Option(‘60’, 111, false,
$(“subject_family_members[]”).options[2]=new Option(‘60’, 111, false,
$(“subject_family_members[]”).options[3]=new Option(‘60’, 111, false,
$(“subject_family_members[]”).options[4]=new Option(‘60’, 111, false,
$(“subject_family_members[]”).options[5]=new Option(‘60’, 111, false,

So, the ‘i’ out of my ‘each_with_index’ is coming through fine, but the
array elements are being broken somehow. Does anyone know what might be
going wrong here?


After a lot of mucking about, i discovered that it seems to be some
problem with ‘each_with_index’ - if i do

<% for option_tag in SubjectFamilyMember.options_for_select([“3”]) -%>

instead, and do the indexing with a local javascript variable then it
seems to work fine, at least in terms of producing javascript using
rhtml tags.

I’d still really like to know why the arrays were all coming out as
[“60”, 111] when i used each_with_index though, in case anyone has any
ideas about that…

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs