Tom
Tom

Reputation: 85

submitting specific form data with RoR link_to and jQuery submit()

I'm unable to figure out how to submit specific data to a Rails update() method via the jQuery submit() method. These is the code snippet I'm working with:

<% form_for(vote, :remote => true) do |f| %>
    <%= check_box_tag "selection", vote.id %>
<% end %>

...

<%= link_to 'Vote Yes', ballots_path, :onclick => "$('.edit_vote').submit()", :class => "buttons" %>
<%= link_to 'Vote No', ballots_path, :onclick => "$('.edit_vote').submit()", :class => "buttons" %>

Essentially there's a boolean field in the Vote table called 'approval' and I want to update this field through the two links above (Vote Yes -> approval=true; Vote No -> approval=false).

Originally I had <%= check_box_tag "selection", vote.id %> as <%= f.check_box :approval %> and I could submit the form with the Yes/No buttons but this is not the functionality I wanted. I need the Yes/No buttons to actually be the approval value, the checkbox is merely there so the user can select which entity to vote on.

This is a picture of what I'm trying to do: https://i.sstatic.net/QZqnw.png

Any ideas about how I'd go about doing this?

Upvotes: 0

Views: 1029

Answers (2)

waldyr.ar
waldyr.ar

Reputation: 15234

Might be because of it's a remote form, which uses a custom onsubmit action. I found a tip on Google on how to fake a click on the submit button instead of submitting the form itself. Like this:

:onclick => "this.form.submit.click();"

This is assuming there is a submit button with name "submit". If you don't have a submit button you can always add one and set display to none to hide it, something like this:

<%= submit_tag 'Opslaan', :name => 'submit', :style => 'display: none;' %>

Upvotes: 3

Jordan Sitkin
Jordan Sitkin

Reputation: 2343

The jQuery .submit() method simply triggers the 'submit' event on the form. In other words, it works the same as clicking a 'submit' button in that form. I'm assuming that you have a form wrapping the whole list with a class of edit-vote.

At first glance, it looks like your first problem is that you may be nesting form tags here. Form tags are not allowed to be nested and if you do so, you'll get some strange and unexpected behavior if they work at all.

Try simply removing the form_for around each checkbox. As long as your update method is written to accept the data you are posting it should work.

Upvotes: 0

Related Questions