7

Selected items in the listbox will show up in the UL below. Click on an item in the UL and it will remove it from the listbox and remove itself from the UL.

Reproduce Bug: http://jsfiddle.net/rkw79/mmBKf/2/

  • Select an item in the listbox
  • Click on that item in the UL, it will disappear and the listbox will show it as unselected
  • Click on that same item in the listbox

Notice that the event is fired, but the item is not added

Now do the same steps, except use .prop('selected','') instead of .removeProp('selected'): http://jsfiddle.net/rkw79/mmBKf/3/

1
  • I guess that prop is direct object properties, different of attr, that work on element attributes. Not? Commented Dec 9, 2011 at 3:19

3 Answers 3

20

Everything you need to know is in the documentation.

With some built-in properties of a DOM element or window object, browsers may generate an error if an attempt is made to remove the property. jQuery first assigns the value undefined to the property and ignores any error the browser generates. In general, it is only necessary to remove custom properties that have been set on an object, and not built-in (native) properties.

Note: Do not use this method to remove native properties such as checked, disabled, or selected. This will remove the property completely and, once removed, cannot be added again to element. Use .prop() to set these properties to false instead.

1
  • Interesting. Worked with an older version of jQuery, once I upgraded, it didn't work. I guess the newer version is just preventing the problem you referred to. Commented Mar 22, 2021 at 15:00
2

You should be using removeAttr()

$('myele").attr('selected'); // <myele /> --> <myele selected />

$('myele").removeAttr('selected'); // <myele selected /> --> <myele />

2
  • UsingremoveAttr breaks my whole code.. Is it possible that you cant doremoveAttr when there is no attribute? Like removeClass doesn't care if there is no class, he will just ignore it.
    – nclsvh
    Commented Aug 26, 2016 at 10:23
  • It's generally recommended to always use prop rather than attr for this kind of thing: stackoverflow.com/a/13626565/1033203
    – Anomaly
    Commented Jun 19, 2018 at 21:22
0

I think you're confusing the html property with the DOM property. I can't think why you'd want to remove the "selected" property. Just set it false:

$('ul').on('click', 'li', function() {
    $('option[value="' + $(this).text() + '"]').get(0).selected = false;
    $(this).remove();
});

EDIT: Grr, I thought those jsfiddles were read only. :-(

Not the answer you're looking for? Browse other questions tagged or ask your own question.