3

As part of an ajax call, I am trying to use embedded ruby to generate the id portion of a jquery select in a .js.erb file. Below is how I got it to work, but I had to use a slight of hand and get the javascript in the browser to concat the id to the selector instead of constructing the jquery selector on the server.

$("tr.design#".concat(<%= @form_column.form_row.id.to_s %>)).html("<%= escape_javascript( render(:partial => "form_rows/row") ) %>")

I tried several combinations:

$(<%= escape_javascript("tr.design#" << @form_column.form_row.id.to_s) %>)

$(<%= "tr.design#" << @form_column.form_row.id.to_s %>)

$("tr.design#<%= @form_column.form_row.id.to_s %>")

in each case the selector returned to the client was $(tr.design#17) (without quotes) and therefore was not executed as I wanted on the client, ie jquery didn't find any matches.

The .html("<%= escape_javascript( render(:partial => "form_rows/row") ) %>") portion was sent to the browser correctly, ie the <%= ... %> behaved as expected and the javascript on the browser received nicely formatted, quoted (and escaped) html passed in the .html function.

Anyone got any ideas on how I could avoid the use of .concat in my .js.erb file?

2 Answers 2

10

Like this

$('#user_<%= @user.id %>').click(blah blah blah);

If you place <%= %> in a js.erb file, that code is evaluated an printed in the resultant JS. You can construct any unique string you want. Probably :classname_:id is most common solution.

By the way, the evaluated code don't has to be an string. <%=%> calls .to_s for printing. In that example, the @user.id is converted into a string.

Sign up to request clarification or add additional context in comments.

1 Comment

(My previous edit took longer than 5 mins....here's the rest of it) I've marked Miguel's as the correct answer simply because the jquery selector is generated on the server and the browser doesn't have to do any concatenation. John's solution produced the desired effect. Thank you both.
0

ids are unique you probably can do

$("#"+<%= @form_column.form_row.id.to_s %>)

2 Comments

does anyone know if this is still possible in rails 4? I'm trying to create a button that closes dynamically created ids (e.g. <button class="button" onclick=$('#item='+<%= comment.id.to_s %>).toggle();>Click to toggle!</button>) but it returns "Uncaught Error: Syntax error, unrecognized expression: #item=57"
@IanDelairre plz create a new question with minimal code example depicting your scenario and problem

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.