Rails Trying to submit a form onchange of dropdown
Asked Answered
T

12

21

I have my Ajax working, builtin Rails javascript, with the submit button. However, I would like it to submit when I change the value of the dropdown box and eliminate the button. In my research I found what looks like the correct solution but I get no request to the server. Here is my dropdown form code, note it still has the submit button that worked before I added :onchange:

<% form_tag('switch_car', :method => :put, :remote => true) do %>
  <div class="field">
    <label>Car Name:</label>
    <%= select_tag(:id, options_from_collection_for_select(active_cars, "id", "name"), 
       :onchange => ("$('switch_car').submit()"))%><%= submit_tag "Switch Car" %>
  </div>    
<% end %>

Here is the HTML generated:

<form accept-charset="UTF-8" action="switch_car" data-remote="true" method="post">
  <div style="margin:0;padding:0;display:inline">
    <input name="utf8" type="hidden" value="&#x2713;" />
    <input name="_method" type="hidden" value="put" />
    <input name="authenticity_token" type="hidden" value="PEbdqAoiik37lcoP4+v+dakpYxdpMkSm7Ub8eZpdF9I=" />
  </div>
  <div class="field"> 
    <label>Car Name:</label> 
    <select id="id" name="id" onchange="$('switch_car').submit()">
      <option value="9">Truck</option>
      <option value="10">Car</option>
    </select>
    <input name="commit" type="submit" value="Switch Car" /> 
</div> 

Thanks in advance for any help.

Tragicomedy answered 5/8, 2011 at 16:25 Comment(3)
What JavaScript library are you using? Your :onchange has Ruby code, it should be a JavaScript call.Ranking
@MauricioLinhares I am using the libraries that install with Ruby on Rails 3. So I need to figure out how to submit the form through javascript?Tragicomedy
Sorry, @MauricioLinhares I see what you are saying. I am now trying to get rails to do it with a remote_function but am still having no luck. I would think this is fairly common though I am having difficulty finding a solution. I just want to submit the form on select?Tragicomedy
T
6

This is what I was able to do to get it to work. I named the form switch_car by using :name => "switch_car" and used the following javascript.

:onchange => ("javascript: document.switch_car.submit();")

I am still looking for a better answer so I will updated if I find something. This doesn't use submit .js for some reason. It processes it as HTML unlike the submit button which uses AJAX to update only the changing page elements. But this is the best I have been able to find so far.

Tragicomedy answered 8/8, 2011 at 15:30 Comment(0)
R
23

Replace your onchange with this,

onchange: "this.form.submit();"
Reichard answered 19/6, 2014 at 19:56 Comment(1)
This will not trigger ajax when using rails-ujs. See my answer below for details.Brenneman
B
21

this.form.submit() will not work if form is remote: true and rails-ujs is in use. In that case, a regular submit will occur instead of XHR.

Instead you should:

onchange: 'Rails.fire(this.form, "submit")'

You can read here for more details.

Brenneman answered 4/4, 2018 at 5:37 Comment(2)
And in Rails 6 Rails isn't exposed anymore... My hair is turning gray over everything constantly deprecating.Ensheathe
To keep it exposed, open your app/javascript/packs/application.js and put it back under global e.g. import Rails from '@rails/ujs'; global.Rails = Rails;.Exospore
T
6

This is what I was able to do to get it to work. I named the form switch_car by using :name => "switch_car" and used the following javascript.

:onchange => ("javascript: document.switch_car.submit();")

I am still looking for a better answer so I will updated if I find something. This doesn't use submit .js for some reason. It processes it as HTML unlike the submit button which uses AJAX to update only the changing page elements. But this is the best I have been able to find so far.

Tragicomedy answered 8/8, 2011 at 15:30 Comment(0)
S
6

This is an old question, but none of the above answers work for me. They all result in a text/html request.

The following works, e.g. (the hide class sets css display: none):

<%= form.radio_button :tier_id, tier.id, onchange: "$('#submit-button-id').click();" %>

together with:

<%= form.submit "Save changes", id: 'submit-button-id', class: 'hide' %>
Sholokhov answered 2/6, 2020 at 8:1 Comment(2)
I will say with a submit_tag you can set the hidden param to be true like "hidden: true" and it will hide the button. This works Rails 6Sarson
This is a quick and obvious way to solve the issue that I had overlooked.Booher
G
5

Depending on the js library you are using:

Prototype: :onchange => ("$('switch_car').submit()")

Jquery: :onchange => ("$('#switch_car').submit()")

If you are using the defaults and your rails version is below 3.1, then prototype is the default library.

Grimsley answered 5/8, 2011 at 19:57 Comment(4)
Thanks. I have version 3.0.9 so I tried the first option. When I make the change in the select box no request is sent to the server. I updated code above. Any idea where I could have gone wrong?Tragicomedy
still no luck with this. Can't figure out why it doesn't send a request to the server?Tragicomedy
install firebug(firefox plugin) to debug, and try executing the javascript manually on firebug console to see if it works, or what the problem is.Grimsley
I use chrome and when I have the javascript console open I can see that nothing happens when I use the prototype code you suggested above. If I put in the javascript: code in from above it works but doesn't do ajax. It responds with a full html refresh.Tragicomedy
B
3

A more general solution using jQuery (I don't need to know the name of the form) is:

onchange: "$(this).parent('form').submit();"
Belgium answered 20/9, 2012 at 17:26 Comment(0)
L
2

This seems to have been around for a while but, I'll post my findings anyway since I haven't found this explanation anywhere yet.

I came across this article which describes quite well what's the problem when triggering a ajax request via the submit() method (with or without jQuery or Handler). The author then recommends to form your own AJAX request. That is not required and shouldn't be done to make use of the logic within rails.js (jquery-jus gem).

Problems with triggering submit() manually occur since rails.js binds and listens to an event that is namespaced submit.rails. To manually trigger a submission use

   onchange: 'javascript: $( this ).trigger("submit.rails")'

on the element or the form.

Lawana answered 25/2, 2015 at 18:13 Comment(0)
E
1

For a select_tag, just add:

{:onchange => "myHandler();" }

where your handler will be:

this.form.submit();

Also, if onchange doesn't work you might want to try onChage with a capital C.

Finally, make sure NOT TO CONFUSE a select_tag with a form select.

See my answer to a similar question, only regarding a form select

Adding An Onchange Event To A Form Select

Electrojet answered 30/9, 2014 at 18:44 Comment(2)
Sorry, but you are messing up select with select_tag. The signature of select_tag is here: apidock.com/rails/v4.1.8/ActionView/Helpers/FormTagHelper/… and there is only one options parameter. Your code example is actually producing an error.Belgium
Thanks Martin you are correct, I will make a distinction between the two.Electrojet
M
1

Time at 2021, with Rails 6

make a hidden submit then use js click() function:

<%= form_with(modle: @user, local: false) do |f| %>
    <%= f.select :menu1, ["option1","option2"], {}, onchange: "javascript:this.form.commit.click();" %>
    <%= f.submit 'save', class: "hidden" %>
<% end>

reference: https://mcmap.net/q/658705/-select-and-onchange-in-a-ruby-on-rails-form

Maclay answered 17/8, 2021 at 16:44 Comment(0)
U
0

If you want to learn rails way ajax submit on fields change here is the code.

<%= select_tag(:id, options_from_collection_for_select(active_cars, "id", "name"), 
data: { remote: true, url: your_ajax_route_path }%><%= submit_tag "Switch Car" %>

data: { remote: true, url: your_ajax_route_path }

will automatically submit your input to your_ajax_route_path. If you are using a form builder then you should use with input_html

input_html: { data: { remote: true, url: your_ajax_route_path } }

like this. I hope it'll be useful for you

Unmarked answered 4/7, 2019 at 10:50 Comment(1)
Why do you need <%= submit_tag "Switch Car" %> if the submission happens on change?Rusk
I
0

None of the solutions was working for me so I used the given below solution.

$("#q_dimension_id_eq").on("change", function (e) {
        $(this).closest("form").submit();
    });
Introrse answered 3/10, 2019 at 7:27 Comment(0)
F
0

I'm using rails 4.2.1 with jquery_ujs and it works for me:

onchange: 'jQuery(this).parent().trigger("submit")'

OBS.: It assumes the element is immediately child from form. You must adjust parent() according your DOM tree.

Ferdinand answered 5/9, 2020 at 20:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.