# Passing a variable to a javascript function from a helper function

**URL:** <https://www.ruby-forum.com/t/passing-a-variable-to-a-javascript-function-from-a-helper-function/188077>\
**Category:** Rails\
**Created:** [May 5, 2010, 12:01pm UTC](https://www.ruby-forum.com/t/passing-a-variable-to-a-javascript-function-from-a-helper-function/188077 "2010-05-05T12:01:27Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Mlle](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/eada6e/32.png) [@Mlle](https://www.ruby-forum.com/u/Mlle)\
**Post date:** [May 5, 2010, 12:01pm UTC](https://www.ruby-forum.com/t/passing-a-variable-to-a-javascript-function-from-a-helper-function/188077/1 "2010-05-05T12:01:27Z")

</div>

I’m trying to pass a variable to a javascript function from a helper  
function but I’m not getting it to work. I think the problem is with  
#{domElement}

any ideas?  
thanks!

This is how the helper function is called from the view:

\<%= link\_to\_add\_fields t(‘form.treatment.add’),  
form, :treatments, :table %\>

Then this is the helper function:

def link\_to\_add\_fields(name, f, association, domElement)  
new\_object =  
f.object.class.reflect\_on\_association(association).klass.new  
fields = f.fields\_for(association, new\_object, :child\_index =\>  
“new\_#{association}”) do |builder|  
render(association.to\_s.singularize + “\_fields”, :f =\> builder)  
end  
link\_to\_function(name, h(“add\_fields(this, “#{association}”,  
“#{escape\_javascript(fields)}”, #{domElement})”))  
end

And this is the javascript function:

function add\_fields(link, association, content, domElement) {  
var new\_id = new Date().getTime();  
var regexp = new RegExp(“new\_” + association, “g”);  
var table = $(link).up(domElement);  
table.insert({  
before: content.replace(regexp, new\_id) });  
}

---

<div class="post-metadata">

**Author:** ![Mlle](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/eada6e/32.png) [@Mlle](https://www.ruby-forum.com/u/Mlle)\
**Post date:** [May 5, 2010, 1:00pm UTC](https://www.ruby-forum.com/t/passing-a-variable-to-a-javascript-function-from-a-helper-function/188077/2 "2010-05-05T13:00:35Z")

</div>

On May 5, 11:00 am, Mlle [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> I’m trying to pass a variable to a javascript function from a helper  
> function but I’m not getting it to work. I think the problem is with  
> #{domElement}

Well you should probably look at the generated javascript and all but  
it looks like you’re not quoting domElement (ie you have just title  
rather than the string literal ‘title’). Passing a fragment of  
javascript through h seems highly dubious - link\_to\_function should be  
taking care of that (but do check!)

Fred
