Skip to content


Custom jQuery UI Rails Button Form Helper

Today I got a little bored with my standard rails buttons

generate secure email button

Not bad…but could use a little pizazz. So I decided to take a crack at jQuery UI. A great javascript and style framework that promised to be easy to use and provides theme-able styles.

Once you’ve got jQuery UI integrated nicely into your rails project (note i had to change my url paths in the stylesheet), you can style your submit button easily by adding some classes just like this:

<%= f.submit "Generate Secure Email", :class => "ui-corner-all ui-state-default " %>

Untitled-3

Though, this isn’t 100% what I was looking for, it’s a good start. When we hover over the button, it changes color, and when we press it, our rails form submits. Though you’ll notice that the cursor doesn’t change when you hover over the button and we haven’t put an icon in it yet. To get the correct behavior i hard coded in a button:

<button id="user_submit" class = "ui-corner-all  ui-state-default"  type="submit" name="commit">Generate Secure Email</button>

Screen shot 2009-10-12 at 9.06.33 PM

This solved the button styling and behavior, but we still don’t have our icon. After browsing the inter webs i found a nice page of jQuery-UI button demos and I managed to modify my code to include a nice icon:

<button id="user_submit" class = "ui-corner-all fg-button ui-state-default fg-button-icon-left" type="submit" name="commit"><span></span>Generate Secure Email</button>

jQuery UI Button with rails

Perfect! It works like a dream, but it’s not very rails-esq. Lets turn this into a reusable chunk of code by making a helper method to extend form builder. In app/helpers/application_helper.rb

class ActionView::Helpers::FormBuilder
    def button_with_icon(text , icon)
     object_name = self.object_name
     return "<button id='#{object_name}_submit' class = 'ui-corner-all fg-button ui-state-default fg-button-icon-left' type='submit' name='commit'><span class='ui-icon ui-icon-#{icon}'></span>#{text}</button>"
    end
end

Now In my View I can put:

<%=  f.button_with_icon("Generate Secure Email", "mail-closed") %>

And I get my perfectly formatted button complete with an Icon!

jQuery UI Button with rails


Note:

<% form_for :person, @person, :url => { :action => "create" } do |f| %>
    <%= f.object_name %>
<% end %>

will print out “person”, thats why in the helper we call  self.object_name on the form_builder class. Pretty cool huh?

Posted in Ruby On Rails, Uncategorized, jquery. Tagged with , , , , , .

0 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

Some HTML is OK

(required)

(required, but never shared)

or, reply to this post via trackback.