Creating Deselectable Radio Buttons with JQuery

A common problem that I’ve often faced (at least as of late) is that of the radio button. In most situations you will want to select one option and move on, but often in Web applications you might select one option but then decide you don’t want to select any or you just mistakenly selected it to begin with. Several times now I have performed searches to see what solutions other people have implemented, but I find some problems with it when trying to use it or I just don’t remember the exact details when I need to implement it another time. What searches turn up a lot is just how to select a checkbox (especially when using JQuery). None of this is very helpful though and it would be nice to have a nice easy reusable solution, which I’ve hopefully crafted for you below.

Now in my example, I am using JQuery to create my radio buttons as I was finding that easier given my circumstances, though I’m sure this can be improved to work for other situations, like adding an inline “onClick” event definition when writing your HTML.

var createRadioClickEvent = function(id, currentValue) {
    if (!createRadioClickEvent.created) {
        createRadioClickEvent.created = {};
    }

    var func = undefined;
    if (createRadioClickEvent.created[id]) {
        func = createRadioClickEvent.created[id];
    } else {
        func = function(event) {
            if ($(event.target).val() === func.selectedValue) {
                $(event.target).attr("checked", false);
                func.selectedValue = undefined;
            } else {
                func.selectedValue = $(event.target).val();
            }
        };
        createRadioClickEvent.created[id] = func;
    }

    if (currentValue !== undefined) {
        func.selectedValue = currentValue;
    }
    return func;
};

Now for this to work, we use a common technique called memoization to record each of the onClick functions as they are created for each radio button set (indicated by the id parameter. This way we are always keeping track of the current selected value. Using the currentValue parameter we are able to pass in whichever value is checked to begin with as we create our radio buttons. Additionally, if we want to extend this further we could add a couple of additional parameters to specify some call backs in cases of selection / deselection.

Now, as a reference, here’s the code I use for creating my radio buttons.

/*
    Options:
        idPrefix - String in differentiating radio button elements
        id - the identifying piece of data to use
        checked - whether the button should default to checked.
        value
*/
function createDeSelectableRadioButton(options) {
    with(options) {
        var selectedValue = checked ? value : undefined;
        var onClick = createRadioClickEvent(id, selectedValue);
        var itemId = idPrefix + id;

        createNamedElement("input type='radio'", id).attr({
            checked : checked,
            value : value,
            id : itemId
        }).click(onClick).insertAfter("label[for='"+ itemId +"']");    }
};

We are utilizing an object argument and using the with() function of javascript to bring its properties to front access. Note that the createNamedElement function is a personal utility function that tries to create a named element in 2 different ways because Internet Explorer has issues if you attempt to set the name attribute after a UI element has already been created.

Hopefully this post has been helpful to solving any issues you might experience with deselecting radio buttons in the future and feel free to leave any additional feedback on how things could be improved further.

New Games Related Blog

Just wanted to mention, if anyone was actually interested, that I’ve just started a new blog to cover my interest in video games and other random junk and it can be found over at Caffeinated Gaming for anyone interested. Feel free to stop by (though there really isn’t anything to see quite yet).