As I was working on my update.js.erb file using Rails 3, I realized that I was repeating a lot of code. To simplify things, I attempted to move it all into a helper function. However, I encountered an issue where the helper was not producing clean JavaScript output. Instead of ", it kept inserting \"
throughout the script.
This is how I initially set up the code:
<% if @list.show_today %>
$("#show_today_check_<%= @list.id %>").removeClass("gray").addClass("orange").attr("value","0");
<% else %>
$("#show_today_check_<%= @list.id %>").removeClass("orange").addClass("gray").attr("value","1");
<% end %>
...
Below is the helper function I created to generate the above JavaScript:
def toggelButtonState( object, name, color)
if object.send(name)
@add_col = color
@rem_col = 'gray'
@value = "0"
else
@add_col = 'gray'
@rem_col = color
@value = "1"
end
js = '$("#'
js += "#{name}_check_#{@list.id}"
js += '").removeClass("'
js += @rem_col
js += '").addClass("'
js += @add_col
js += '").attr("value","'
js += @value
js += '");'
end
Calling the function like this:
<%= toggelButtonState( @list , 'show_today', 'orange' ) %>
Results in the following response:
$(\"#show_today_check_2\").removeClass(\"orange\").addClass(\"gray\").attr(\"value\",\"1\");
I noticed a similar issue with HTML content in helpers and discovered the use of content_tag
. Is there an equivalent method for handling JavaScript? How can I eliminate the insertion of \"
's?