Search code examples
javascriptjqueryruby-on-railsajaxsimple-form

Rails 5 ajax form: submit form on clicking one of the 2 radio buttons in Ajax


Note: Similar questions exist but none of them resemble my case

I am making a small Ajax form in my rails views with yes or no radio buttons, I made this form with remote: true and it acts correctly as Ajax if I use a separate submit button (no page reload happens & form is passed to controller)

If I use Jquery to make the radio buttons themselves submit the form, then it submits but not in Ajax (but with a page reload)

So how to fix this to:

Submit form on clicking one of the 2 radio buttons in Ajax?

The two things I tried:

1) Make two different submit buttons & try to adjust the form value in the submit btn itself, if I make them as submit buttons, Ajax works well but the form doesn't get my required value

    <div class="radio-button-btn-wrapper mr-2">
      <%= f.submit t('yes'), recommended: true,  class: "radio-button-btn-label-white background-green"  %>
    </div>
    <div class="radio-button-btn-wrapper mr-2">
      <%= f.submit t('no'), recommended: false, class: "radio-button-btn-label-white background-red" %>
    </div>

2) Adjust the radio buttons to submit the form in Ajax manner (tried this but it didn't work)

  <%= simple_form_for [...model names], remote: true do |f| %>
  <div class="flex">

    <div class="radio-button-btn-wrapper mr-2">
      <%= label :recommended, t('yes'), class: "radio-button-btn-label white" %>
      <%= f.radio_button :recommended, true, onclick: "$(this).closest('form').submit();", class: "radio-button-btn background-green" %>
    </div>
    <div class="radio-button-btn-wrapper">
      <%= label :recommended, t('no'), class: "radio-button-btn-label white" %>
      <%= f.radio_button :recommended, false, onclick: "$.ajax((this).closest('form').submit());", class: "radio-button-btn background-red" %>
    </div>
  </div>

Solution

  • After extensive searching for why this happens & how to fix it in the easiest way, I found this issue in Rails 5.2 & thanks to this solution from Padi we should use this code to make it work as expected:

    // Get hold of the form object
    form = document.querySelector('form');
    // Use the Rails fire helper 
    Rails.fire(form, 'submit');