RJS: how to find which button was clicked

On a normal form one could use this logic to get which submit button was
clicked.

if params[:commit].include? "Preview"
   # do something
elsif params[:commit].include? "Post"
 # do something
else
  # do something

end

But if I use RJS and form_remote_tag then the above logic will not work.

I was wondering if anyone has any solution on how to find which button
was
clicked when form_remote_tag is being used.

Thanks.

  • Raj

Raj S. wrote:

But if I use RJS and form_remote_tag then the above logic will not work.

I was wondering if anyone has any solution on how to find which button
was
clicked when form_remote_tag is being used.

Thanks.

  • Raj

I had the same problem. This is actually a prototype issue because
prototype ends up passing all of the submit buttons when a form is
submitted via AJAX. Until prototype is fixed (if it ever will be?), I
put a hidden field in my form that contains the value of the button
clicked. Each submit button has assigns a value to the hidden field
when it is clicked:

<%= hidden_field_tag ‘which’, ‘’ %>
<%= submit_tag ‘Button1’, {:onclick => “$(‘which’).value = ‘button1’;”}
%>
<%= submit_tag ‘Button2’, {:onclick => “$(‘which’).value = ‘button2’;”}
%>

In my controller, I can then check the ‘which’ parameter to see which
button was clicked. Note, however, that this method only works with
javascript enable, so you still have to drop back to checking for submit
buttons if ‘which’ is empty:

if params[:which].empty?
#javascript must be disabled
#handle params[:commit] to see which button was clicked
else
#javascript is enabled
#handle params[:which] to see which button was clicked
end

Thanks Curtis. Thanks for posting the code and mentioning that it was
prototype issue. I thought I was missing something here.

-=- Raj