Rails 3: How to trigger a form submission via javascript?

后端 未结 5 1288
逝去的感伤
逝去的感伤 2020-12-30 08:25

I have a form that for the most part just submits as a normal form, so I don\'t want to set in the form_tag the :remote => true option.

However, under certain circum

相关标签:
5条回答
  • 2020-12-30 09:07

    I just tried this which definitely works, if the form has remote => true, just remove the data-remote attribute to submit normally w/ javascript ie

    $('input').click(function(){ $('#form').removeAttr('data-remote') });
    

    I'm guessing the opposite would probably work ie if the form doesn't have remote => true just do

    $('input').click(function(){ $('#form').attr('data-remote',true)});
    
    0 讨论(0)
  • 2020-12-30 09:14

    I'm sorta new to this but here goes...

    rails.js (the jquery one at least) defines the following function to catch and submit forms:

    $('form').live('submit.rails', function(e) { ... });
    

    If you use the following it should trigger the same function (and if :remote => true, then it wont cause a page reload):

    $("#<yourformid>").trigger("submit.rails");
    

    So, if you wanted to submit your form on a select change for example, you could set the above trigger call to the select's :onchange I would imagine.

    0 讨论(0)
  • 2020-12-30 09:15

    If you're using jQuery you could do something like this to have the form auto-post on keyup events, or simplify it to trigger manually:

      $(function() {    
        $("#live_search input").keyup(function() {
            q = $('#search_text').val();
          $.ajax({
              beforeSend      : function(request) { request.setRequestHeader("Accept", "text/javascript"); },
                               // Included so Rails responds via "format.js"
              data          : 'query=' + q,
              success       : function(data, textStatus, XMLHttpRequest) {
                                    // alert(textStatus);
                                    $("#live_search #results").html(data);
                                    },
              error         : function(XMLHttpRequest, textStatus, errorThrown) {
                                    // alert(errorThrown);
                                    $('#annotation_dialog').html(XMLHttpRequest.responseText);
                                    },
              type            : 'POST',
              url                 : '/search/live'
          });
          return false;
        });
    });
    
    0 讨论(0)
  • 2020-12-30 09:16

    maybe u could try this:

    $('#form').submit();
    
    0 讨论(0)
  • 2020-12-30 09:16

    In Rails 5 (which replaces jquery-ujs with rails-ujs), this is how you trigger the handler rails attaches to a form's submit event:

    var elem = document.getElementById('myform') // or $('#myform')[0] with jQuery
    Rails.fire(elem, 'submit');
    

    (Holy cow did it take me forever to figure that out!)

    0 讨论(0)
提交回复
热议问题