Rails link_to ruby ​​variable in onclick javascript

What is wrong with this statement. It shows a syntax error.

<%= link_to image_tag('cancel.png'), {:action => 'remove', :id => question.id}, :title=>'Delete', :class=>'action', :onclick=>"removeQuestion("+ question.id +");return false;"%> 

But

 <%= link_to image_tag('cancel.png'), {:action => 'remove', :id => question.id}, :title=>'Delete', :class=>'action', :onclick=>"removeQuestion();return false;"%> 

correctly generates the code below

 <a title="Delete" onclick="removeQuestion();return false" class="action remove" href="/quizzes/remove/1"><img src="/images/cancel.png?1290165811" alt="Cancel"></a> 
+6
ruby-on-rails
source share
2 answers

What did you write

 <%= link_to image_tag('cancel.png'), {:action => 'remove', :id => question.id}, :title=>'Delete', :class=>'action', :onclick=>"removeQuestion("+ question.id +");return false;"%> 

This bomb, because question.id is Fixnum. You will get can't convert Fixnum into String TypeError .

Ways to solve this problem

 <%= link_to image_tag('cancel.png'), {:action => 'remove', :id => question.id}, :title=>'Delete', :class=>'action', :onclick=>"removeQuestion("+ question.id.to_s +");return false;"%> 

OR

 <%= link_to image_tag('cancel.png'), {:action => 'remove', :id => question.id}, :title=>'Delete', :class=>'action', :onclick=>"removeQuestion('#{question.id}');return false;"%> 

This will send the question id as a string to your removeQuestion javascript function.

OR

 <%= link_to image_tag('cancel.png'), {:action => 'remove', :id => question.id}, :title=>'Delete', :class=>'action', :onclick=>"removeQuestion(#{question.id});return false;"%> 

This will send the question id as an integer to your removeQuestion javascript function.

+10
source share
  <%= link_to image_tag('cancel.png'), {:action => 'remove', :id => question.id}, :title=>'Delete', :class=>'action', :onclick=>"removeQuestion($(this).attr('id'));return false;"%> 

It will work

+1
source share

All Articles