2

I'm using Rails 3.1 and I need a checkbox to toggle and save to the database without the page refreshing or redirecting.

Let me preface by saying i'm fairly novice, if i'm coming at this problem from the wrong angle please let me know.

Here is my form:

<% form_for book, :remote => true do |f| %>
   <%= f.check_box :finished %>
<% end %>

Here is my jQuery javascript:

$('input#book_finished').live("click", function() {
    $(this).parent('form').submit();
});

The :remote = > true doesn't work when I submit via jQuery, but does if I throw in a submit button (which I can't have). How can I submit on clicking the checkbox though JS?

2
  • Your JS should submit the form just fine. Of course in this case you'd have to handle the response as well yourself. What exactly happens? Commented Sep 19, 2011 at 7:37
  • It submits, then redirects to the show page ( I'm using a standard restful scaffold). I tried changing the controller so there is no redirect and I get a missing template error. Commented Sep 19, 2011 at 17:57

1 Answer 1

3

Your code so far only handles the submitting via a click on the checkbox. In order to submit the form via AJAX, you'll still have to catch the submit event, prevent the default behavior and send the form data:

$('#form-id').submit(function(){
  $.ajax({
    type: this.method,
    url: this.action,
    data: $(this).serialize(),
    success: function(){
      ... // do something in case everything went find
    }
  });
  return false;
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.