Natali Brito
Natali Brito

Reputation: 50

how to handle a submit with two different forms or methods

I have a checkbox outside a form and for this to work I use the form with an id, like this:

My form with the id:'check-form'

<%= form_for(:execution, url:{controller:"executions", action:'create_multiple'}, html:{id:"check-form", class:"form-inline"}) do |form| %>
    <div class="input-group mb-3">
        <%= form.select :collaborator_id,@collaborators.collect 
           { |collaborator| [collaborator.name, collaborator.id] },
           {prompt: 'Selecione'}, {class:'form-control', required:true} %>
        <div class="input-group-append">
            <%= button_tag(type: "submit", class: "btn btn-raised btn-primary", form:'check-form') do %>
                <span><i class="far fa-play-circle"></i> Play</span>
            <% end %>
        </div>
    </div>
<% end %>

My checkbox with form:'check-form'

<%= check_box_tag 'execution[status_id][]', item.sector_status(sector.id).id, checked:false, 
{id:"check-#{item.sector_status(sector.id).id}", form:'check-form'}%>

What I want is to be able to use the value of the checkbox in another form with another method. Is there any way I could do this or maybe use a function to make the form "work" with two possible methods?

Upvotes: 0

Views: 229

Answers (2)

arieljuod
arieljuod

Reputation: 15838

You can use one form and submit it with differnt methods using the attribute "formmethod" for buttons with type=submit since HTML5.

<form .....>
  <button type='submit' formmethod='post'>Sends a POST request</button>
  <button type='submit' formmethod='get'>Sends a GET request</button>
</form>

Formmethod attribute can be ignored for the buttons that matches the form's method attribute.

Upvotes: 1

Billy Kimble
Billy Kimble

Reputation: 820

I would set up a hidden field in both of the forms, and add a class to them:

<%= hidden_field_tag('execution[status_id][]', item.sector_status(sector.id).id, {class: 'my_checkbox_value'}) %>

Then create a dummy checkbox outside the forms that, when clicked, assigns a value to those hidden fields:

<%= check_box_tag('dummyCheckbox', someValue , yourClickedValue, {id: 'my_dummy_checkbox') %>

Finally bring it all together with a jQuery click handler:

$("#my_dummy_checkbox").click(function() {
  if ($(this).prop("checked") == true) {
    $(".my_checkbox_value").val($(this).attr("value"))
  } else {
    $(".my_checkbox_value").val("")
  }
})

Now when your forms are submitted, the hidden field will have the value of the checkbox if it was clicked, or it will be empty if it was not.

Upvotes: 2

Related Questions