6

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/

Shadow The GPT Wizard
  • 66,030
  • 26
  • 140
  • 208
rkw
  • 7,287
  • 4
  • 26
  • 39

3 Answers3

19

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.

Community
  • 1
  • 1
RightSaidFred
  • 11,209
  • 35
  • 35
  • 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. – dougd_in_nc Mar 22 '21 at 15:00
2

You should be using removeAttr()

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

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

Terry
  • 14,099
  • 9
  • 56
  • 84
  • Using`removeAttr` breaks my whole code.. Is it possible that you cant do`removeAttr` when there is no attribute? Like removeClass doesn't care if there is no class, he will just ignore it. – nclsvh Aug 26 '16 at 10:23
  • It's generally recommended to always use prop rather than attr for this kind of thing: https://stackoverflow.com/a/13626565/1033203 – Anomaly Jun 19 '18 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. :-(

JayC
  • 7,053
  • 2
  • 25
  • 41