How to add icons to submit buttons using jQuery and jQuery-UI

by Charles Cherry

If you are using the jQuery-UI css framework, you know that you can style buttons to make them more attractive and match your current UI theme. For example, you can make this kind of button:

Look like this:

simply by adding “class=’button'” to the tag, and then running this jQuery code snippet:

$(function () {
    $(".button").button();
});

You can also add icons to your buttons, too:

$(function () {

    $("#searchButton").button({
            text: true,
            icons: { primary: "ui-icon-search" }
        });
});

You end up with a button that looks like this:

(or like this, in a modern browser: )

But adding icons only works for non-input elements, i.e., button, span, anchor, div, etc., (just about anything other than an <input /> tag).

In order to add an icon to a button-styled input element, you have to do some tricky workarounds. (I got part of this workaround from a comment by Robert Mullaney in this article:

http://www.robertmullaney.com/2010/11/29/style-submit-and-reset-buttons-with-icons-using-jquery-ui/

Here is how I add icons to my ‘<input type=”submit” ‘ elements:

1. First, add a custom “icon” attribute to your input tag using the name of the icon you want to display as the attribute’s value:

<input id=”saveButton” type=”submit” value=”Save” icon=”ui-icon-disk” />

In this case I want to display a “disk” icon next to the text of my “Save” button.

2. Add the following jQuery code to your page’s start-up script. I usually put this in my “master” page or “layout” view, so that it operates on every page in my site.

$('input[type="submit"]').each(function () {
   $(this).hide().after('<button>').next().button({
        icons: { primary: $(this).attr('icon') },
        label: $(this).val()
    }).click(function (event) {
         event.preventDefault();
         $(this).prev().click();
    });
});

You end up with real submit buttons that look like this:

This code iterates through all “input type=submit” elements on the page, and then adds the necessary tagging to make the button goodness work.

The bold part is where the custom attribute comes into play. If the element has an attribute named “icon”, it grabs the value of that attribute and hands it to the icon option of the button function.

The rest of the code is standard jQuery stuff – it binds to the click event of the new button tagging, which then triggers the click event of the parent input element whenever the button is clicked.

Very tricky, but it works! (At least it works for me, and I’ve tested it in Chrome and IE-7/8. I can’t vouch for any other browsers out there.)

Note: Using an image editor, I modified the default icon files that ship with jQuery-UI to use colored icons instead of the standard (ugly) monochrome icons.

Advertisements