Skip to main content
Source Link

I wrote a jQuery plugin for setting and getting radio-button values. It also respects the "change" event on them.

(function ($) {

    function changeRadioButton(element, value) {
        var name = $(element).attr("name");
        $("[type=radio][name=" + name + "]:checked").removeAttr("checked");
        $("[type=radio][name=" + name + "][value=" + value + "]").attr("checked", "checked");
        $("[type=radio][name=" + name + "]:checked").change();
    }
    
    function getRadioButton(element) {
        var name = $(element).attr("name");
        return $("[type=radio][name=" + name + "]:checked").attr("value");
    }
    
    var originalVal = $.fn.val;
    $.fn.val = function(value) {
        
        //is it a radio button? treat it differently.
        if($(this).is("[type=radio]")) {
            
            if (typeof value != 'undefined') {
        
                //setter
                changeRadioButton(this, value);
                return $(this);
        
            } else {
                
                //getter
                return getRadioButton(this);
                
            }
            
        } else {
            
            //it wasn't a radio button - let's call the default val function.
            if (typeof value != 'undefined') {
                return originalVal.call(this, value);
            } else {
                return originalVal.call(this);
            }
            
        }
    };
})(jQuery);

Put the code anywhere to enable the addin. Then enjoy! It just overrides the default val function without breaking anything.

You can visit this jsFiddle to try it in action, and see how it works.

http://jsfiddle.net/ffMathy/MN856/