Thursday, December 30, 2010

jQuery 1.4.4 - issue with attr('selected', null)

Issue:
The code below worked before under version jQuery 1.4.2 but when I upgraded to version 1.4.4 it no longer worked as expected - it did not unselect the list box item, only setting "selectd" worked:
        _handleClick: function(elem) {
            var self = this; var initElem = this.element;
            var checked = $(elem).attr('checked');
            var myId = elem.attr('id').replace(initElem.attr('id') + '_chk_', '');
            initElem.children('option[value=' + myId + ']').attr('selected', function() {
                if (checked) {
                    return 'selected';
                } else { return null; }
            });

            if ($.isFunction(self.options.onItemSelected)) {
                try {
                    self.options.onItemSelected(elem, initElem.children('option').get());
                } catch (ex) {
                    if (self.options.allowDebug)
                        alert('select function failed: ' + ex.Description);
                }
            }
        },
Solution:
Under jQuery 1.4.4 you need to explicitly remove the attribute as in "removeAttr('selected'):
        _handleClick: function(elem) {
            var self = this; var initElem = this.element;
            var checked = $(elem).is(':checked');
            var myId = elem.attr('id').replace(initElem.attr('id') + '_chk_', '');
            if (checked) {
                initElem.children('option[value=' + myId + ']').attr('selected', 'selected');
            } else {
                initElem.children('option[value=' + myId + ']').removeAttr('selected');
            }
            if ($.isFunction(self.options.onItemSelected)) {
                try {
                    self.options.onItemSelected(elem, initElem.children('option').get());
                } catch (ex) {
                    if (self.options.allowDebug)
                        alert('select function failed: ' + ex.Description);
                }
            }
        },

No comments:

Post a Comment