Get AJAX checkbox value in Rails-UJS

644 views Asked by At

When I try submitting an AJAX checkbox I'm not getting the value passed as a parameter if the checkbox isn't checked. I know in normal forms Rails adds a hidden field with the same name and value 0 for checkboxes but that doesn't work here because only the one input is serialized not the whole form.

<input type="checkbox" name="task[1]" id="task_1" value="1" data-url="/tasks/update" data-remote="true" data-method="patch">

I'm using Rails-UJS as described: https://guides.rubyonrails.org/v5.2/working_with_javascript_in_rails.html#data-url-and-data-params

I also found this in JQuery-UJS: https://github.com/rails/jquery-ujs/wiki/Unobtrusive-scripting-support-for-jQuery-%28list-of-data-attributes%29#data-url

This issue discusses it and @yourivdlans proposed a pull request with a solution but still not accepted over a year later

Log file might look like:

Clicking checkbox on:

Started POST "/tasks/1" for ::1 at 2020-02-27 15:55:37 +0000
Processing by TestController#test as JS
  Parameters: {"task"=>"1", "id"=>"1"}

Clicking checkbox off:

Started POST "/tasks/1" for ::1 at 2020-02-27 15:55:52 +0000
Processing by TestController#test as JS
  Parameters: {"id"=>"1"}
1

There are 1 answers

2
max On

I would just create a form and an event handler that submits the form when the input is changed:

<% form_for task, remote: true do |f | %>
  <%= f.check_box :completed, class: 'submit-on-change' %>
<% end %>
// put this in the assets pipeline / webpacker
document.addEventListener('change', function(e){
  if (e.target.matches('.submit-on-change') && e.target.form){
    e.target.form.submit();
  }
});

It's a lot less messy then trying to get Rails-UJS to handle the gotchas involved with checkboxes.