Aaron
Aaron

Reputation: 4480

Rails checkbox create a submit action

I have a rails form with checkboxes. What I am trying to do is when the user clicks on a check box the app deletes that entry from the database. What I cannot figure out is how to have the app react when the user checks on the check box (similar action to having a submit button clicked). What should I include in my html so when the user click on a check box the app does something?

Here is my code

<% @items.each do |item|%>
    <%if item.email == @user.email%>
        <%= form_for @item do |f| %>
            <%= f.check_box :to_do %>
            <%= f.label item.to_do %><br />
        <% end %>
    <%end%>
<%end%> 

I am iterating through items and if there is a match between the item.email and user email print out the item with a check box next to it. I can include more code if needed. Is there an Ajax call I can make?

Upvotes: 1

Views: 3196

Answers (3)

borbesaur
borbesaur

Reputation: 691

As RedBassett said, I'm not 100% sure I agree with the strategy of having a checkbox instantly delete an entry. However, if that form you have is already set up to delete things, you can do it like this:

You don't even need an AJAX call. Just regular Jquery. Add a class to the form, as well as to the checkbox

 <%= form_for @item do |f|, :class => "form-class" %>

 <%= f.check_box :to_do, :class => "checkbox-class" %>

and in your JS file, use Jquery to tell the form to submit when the user clicks the checkbox.

$(".checkbox-class").on("click", function (){
  $(".form-class").submit();
});

Note: this will actually submit the form, it will be as if you checked the box and then pressed a 'submit' button, so you will need to handle the form submission in the controller, if you want to stay on the same page, you will need to redirect back to the same page as this action will cause a reload/redirect

Upvotes: 2

Sergio Gonzalez
Sergio Gonzalez

Reputation: 2190

Use borbesaur answer, but remember you can just add the remote: true option to your form so Rails can submit the form using ajax and you avoid reloading all the page again. :)

Upvotes: 0

Jayaprakash
Jayaprakash

Reputation: 1403

Yes. You can write an AJAX call.

<script>
     $('#checkbox_id').change(function(){
        $.get('controller/action?item_id='+$(this).val(), function(data, status){
           /* Call back */
        })
     })
</script>

Upvotes: 0

Related Questions