开发者

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

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 circumstances I'd like to be able have a javascript function p开发者_如何学Goost the form as if it had been posted by :remote => true. What would I need to do in javascript to accomplish this?


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.


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)});


maybe u could try this:

$('#form').submit();


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;
    });
});


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜