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

Posted by Renso on Geeks with Blogs See other posts from Geeks with Blogs or by Renso
Published on Thu, 30 Dec 2010 17:57:14 GMT Indexed on 2010/12/30 18:55 UTC
Read the original article Hit count: 174

Filed under:

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);
                }
            }
        },
 

© Geeks with Blogs or respective owner