views:

325

answers:

2

I'm trying to submit a rails form using a submit trigger that is outside of the form tags. So I have my form:

<% remote_form_for Package.new, 
:url => { :action => :rate_shop, :ids_sales_order_id => params[:ids_sales_order_id],
:id => @shipment.id }, :loading => '$("#loading").overlay({api: true}).load(); ' + visual_effect(:appear, 'priceShopInProgress'), 
:complete => visual_effect(:fade, 'priceShopInProgress', :duration => 2), 
:update => 'itemSelection' do |f| %>

And I have my jQuery:

$('#priceSelectSubmit').click(function() {
  $('#new_item').submit();
});

And my trigger:

<%= submit_tag :Submit, :value => 'Select item', :id => 'priceSelectSubmit', :name => 'priceSelectSubmit' %>

Here's the deal. The submit button submits the form correctly (and loads a new page with all the right data) but does not fire off the form like it would if the button were within the form tags (specifically the :loading stuff is pretty important). I need that AJAX response and the overlay to load, etc.

My contraints:

  • Must use jQuery with Rails
  • Submit button can not be within form
  • I am not the main programmer on this (he is out of action atm) so I don't know if it's just a simple tweak of my jquery to get the form to fire correctly, or if it requires moving the "action" stuff out of the form tag and into a jquery function. Any thoughts? Very appreciated!
A: 

You could try using the onsubmit() call instead:

$('#priceSelectSubmit').click(function() {
  $('#new_item')[0].onsubmit();
});

The onsubmit function is called when you "submit" the form via a user action, but is typically bypassed when you call the submit method on the form directly.

If you view the actual HTML generated, you can see the Ajax call made inside the onsubmit="..." block.

Edit: Amended to de-reference the jQuery proxy object.

tadman
I get "onsubmit" is not a function in firebug :-/
James M
Upon reviewing other StackOverflow questions, it seems like it's impossible to get jquery to fire a form with onsubmit. That's odd. Is it true?
James M
Actually, I had a bit of a brain fail there and forgot to de-jQuery the reference. You should be able to do it by: $('#new_item')[0].onsubmit() where the [0] is used to identify the first matching element and return the actual DOM object. Otherwise you just get the jQuery wrapper object.
tadman
+1  A: 

Ok so I figured it out from repeated googling. And thanks tadman for sending me down the right path!

$('form').trigger('onsubmit')

That's how jQuery lets you submit a form as if a user clicked submit.

James M