ccurtis
ccurtis

Reputation: 35

How can I use embedded ruby to dynamically create a jquery selector (in a .js.erb file)?

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?

Upvotes: 3

Views: 4855

Answers (2)

miguel.camba
miguel.camba

Reputation: 1827

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.

Upvotes: 10

John x
John x

Reputation: 4031

ids are unique you probably can do

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

Upvotes: 0

Related Questions