Rails Trying to submit a form onchange of dropdown

后端 未结 11 1255
遥遥无期
遥遥无期 2020-12-13 20:28

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 b

相关标签:
11条回答
  • 2020-12-13 21:06

    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.

    0 讨论(0)
  • 2020-12-13 21:12

    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.

    0 讨论(0)
  • 2020-12-13 21:12

    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

    0 讨论(0)
  • 2020-12-13 21:14

    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.

    0 讨论(0)
  • 2020-12-13 21:21

    Replace your onchange with this,

    onchange: "this.form.submit();"
    
    0 讨论(0)
  • 2020-12-13 21:21

    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' %>
    
    0 讨论(0)
提交回复
热议问题