snovosel
snovosel

Reputation: 91

submit form by only clicking checkbox

I am trying to create on my view the submission of a checkbox (it's a toggle of an attribute) by only clicking the checkbox itself, and without having to use the submit button.

This is what I have for my text box/submit:

<%= form_for @task, remote: true do |task| %>
    <%= task.check_box :complete, class: "check_box" %>
    <%= task.submit %>
<% end %>

When I only click the box, I would like to trigger this method:

def update
    @task = Task.find(params[:id])

    @task.toggle :complete
    @task.save

   respond_to do |format|
      format.html
      format.js
    end

  end

I'm wondering if any of you think that creating a link_to with a div would be an easier solution to this problem, otherwise I would like to use jquery or some other method and keep the check box.

Thank you!

Upvotes: 0

Views: 2848

Answers (2)

Elias Glyptis
Elias Glyptis

Reputation: 530

To to submit form upon selecting checkbox you can simply add onchange: "this.form.submit();" and it will submit the form and load the next action.

<%= form_for @task, remote: true do |task| %>
  <%= task.check_box :complete, class: "check_box", onchange: "this.form.submit();" %>
  Yup I am done!
<% end %>

Upvotes: 1

titan
titan

Reputation: 676

Its simple, see this script for help:

$(".check_box").change(function(){
  if($(this).prop('checked') == true){
    $("form").submit();
  }
});

You might want to check if the checkbox is being checked ON or OFF.

Upvotes: 0

Related Questions