Rails + jQuery - Using jQuery to submit the form w/o the Submit button
Given:
<%=form_for [:project, @note], :remote => true do |f| %>
I'd like to create a jquery bind that automatica开发者_如何学JAVAlly saves every few seconds. I'm not worried about the timing part yet, just how to use jquery to submit the form automatically (ie, not submit button click by the user.)
I tried this, but it isn't working. Suggestions?
$('form[data-remote]').live('submit', function (e) {
alert(1);
e.preventDefault();
});
Thanks!
So you are talking about something like Autosave, right?
Maybe you want to specify a Javascript interval to this. An example could be:
var autosave = window.setInterval("autosaveForm()", 1000);
function autosaveForm() {
$('form[data-remote]').submit();
}
What this does is to call autosaveForm()
every second and submits the form. To stop the autosave you could just use clearInterval
like this:
window.clearInterval(autosave);
I hope this helps.
$('form[data-remote]').submit()
will submit the form.
Start with setInterval:
setInterval(transmit, 3000);
Which calls this function:
function transmit(){
// get the form field data
var params = {
formField1:$("input#formField1").val(),
formField2:$("input#formField2").val()
}
// make the ajax call
var url = "/controller/action";
$.post(url, params,
function(response, status){
//display results(response, status);
});
}
What version of jQuery are you using? Are you using IE? The early versions of live() didn't work with IE for form submits. (See http://github.com/rails/jquery-ujs/issues/issue/8)
I think I ended up using this:
if (jQuery.browser.msie){
$("form[data-remote]").delegate("input[type='submit'],button[type='submit'],input[name='commit']", 'click', function(e) {
$(this).parents("form[data-remote]").submit();
if(e.preventDefault) e.preventDefault();
});
}
in a project.
精彩评论