Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 post the form as if it had been posted by :remote => true. What would I need to do in javascript to accomplish this?

like image 525
William Jones Avatar asked Feb 04 '11 23:02

William Jones


People also ask

How do you submit a form using JavaScript?

In the body tag, created an HTML form and specify the id, method, and action of the form. In the form, specify an anchor tag with an event onclick. Create a function for JavaScript that will get executed when the link is clicked. When we click on the link, the function submitForm() will get executed.

Which method is used to submit forms in JavaScript?

The formmethod attribute defines the HTTP method for sending form-data to the action URL. The formmethod attribute overrides the method attribute of the <form> element. The formmethod attribute is only used for buttons with type="submit".

What triggers form submit?

Hitting enter on text fields can sometimes trigger a form submit. See here. Especially if that is the only element in the form. One way to control the post back is to set the action to empty and fire off the event yourself with Javascript.

What happens on form submit JavaScript?

The submit event fires when the user clicks a submit button ( <button> or <input type="submit">) or presses Enter while editing a field (e.g. <input type="text">) in a form. The event is not sent to the form when calling the form. submit() method directly.


1 Answers

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.

like image 153
brachyceros Avatar answered Oct 27 '22 01:10

brachyceros