jQuery Mobile, Rails, Buttons and Headaches
So I wanted to add a button to my Rails 3.1 / jQuery Mobile app that triggered an AJAX action (HTTP POST). It should have been easy…
Firstly, I tried <button_to>… however this creates a form. The problem I had was that jQuery Mobile was triggering on POST and one GET for each click. In theory you can add ‘data-ajax=false’ to tell jQuery Mobile to leave this alone – however there is no way in the button_to helper to add attributes to the <form> tag (they all get added to the child <input> tag.
So I changed the ‘button_to’ to a ‘link_to’ (with :method => :post) and things seemed to go swimmingly at first.
However a little down the track I wanted to be able to disable/enable this button. in jQuery Mobile I could easily do this by calling $(‘…’).button() followed by $(‘…’).button(‘disable’) – however I ran into two problems. Firstly there was no easy way to have the button disabled on initial page load (I could run that but of JS on page load – but I really just wanted to add “disabled” to the button element.) Secondly, since link_to still included the underlying link after jQuery Mobile had styled it to look like a button – calling ‘disable’ made it look disabled but really didn’t disable it at all.
A simple button was causing me a lot of headache. It seemed that the ‘right’ element to use here was in fact a ‘button’ (since it was semantically correct and it had the correct ‘disable’ functionality). The problem became how to add ‘data-ajax=false’ to the form generated by the button_to helper.
My current workaround is simply to create the form directly each time I want a button. It looks something like this:
<%= form_for @event, :url => :undo_event, :remote => true, :method => :post, :html => { :class => “button_to”, “data-ajax” => “false” } do |f| %>
<%= f.submit “Undo?”, :class => “undo-button”, :disabled => true, “data-icon” => “back”, “data-iconpos” => “top” %>
<% end %>
I guess the other approach would be to make a helper that looked like ‘button_to’ except that it allowed options to be passed to the parent form.
Recent Comments