0

I have a form for multiple pupils, with checkboxes next to each pupil to collect their IDs. I'm trying to have two buttons that each lead to different forms, and I've tried submitted params with the button click but to no avail:

simple_form_for - multiple submit buttons with different params

Is there any way to write some JS that adds a parameter to the params before submitting the form? My form is as follows:

<%= simple_form_for :pupils, url: edit_multiple_school_group_pupils_path(school, group) do |f| %>
  ...
  ...
  <%= f.button :submit, 'Change Levels', name: 'editing', value: 'levels' %>
  <%= f.button :submit, 'Move to A Class', name: 'editing', value: 'classes' %>
<% end %>

Each of the buttons have their own ID in the raw HTML so I'm hoping theres a way to pluck that before the form gets submitted and add it to the params.

I'm extremely green with JS so wouldn't even know where to start. Thanks in advance.

Mark
  • 6,112
  • 4
  • 21
  • 46

1 Answers1

0

I'm not 100% sure what is needed for the rails portion, but it sounds like you want to serialize your form.

This is fairly easily accomplished. Here is an example of what a serialize to JSON function might look like

function toJSONString( form ) {
    var obj = {};
    var elements = form.querySelectorAll( selectors );
    for( var i = 0; i < elements.length; ++i ) {
        var element = elements[i];
        var name = element.name;
        var value = element.value;

        if( name ) {
            obj[ name ] = value;
        }
    }

    return JSON.stringify( obj );
}

The selectors can be pretty much whatever you want within your form. Inputs, textareas, buttons etc.

Hope this helps!

  • Sorry but I really struggle with JS - would this code add the variable to the parameters before their submitted to the rails server? – Mark Aug 09 '17 at 09:28
  • 1
    All the above code would do is serialize your form into a JSON object. You mentioned that the buttons have their own ID's. You should be able to define the selectors and grab those as well. – breadstickguy Aug 09 '17 at 16:02