Chrome is not an update item with multiple items

I have a very simple element in my HTML:

<select multiple="multiple" size="19" name="Title[book_types_array][]" id="Title_book_types_array"> <option value="0">None Selected</option> <option value="1" selected="selected">Textbook School</option> <option value="2">Textbook Undergraduate</option> </select> 

And I have a bit of jQuery that magically allows you to select one click:

 $('select[multiple] option').click(function(e){ var self = $(this); e.preventDefault(); if (self.attr('selected')) self.removeAttr('selected'); else self.attr('selected', 'selected'); }); 

And it works just dandy in Firefox, but not in Chrome.

It technically works in Chrome, but does not update the item. As an example, I select two options, and then deselect them, it still shows them as selected. However, when I select a new option in an element, it now updates and deselects two elements that I have not selected previously. It will also update the item if I click on another window and then again.

Is this some kind of bug in Chrome with this element or is something missing?

Edit

When I look in the console, I see how it removes the selected attribute, it just does not refresh the element.

Added example: http://jsfiddle.net/Udf5c/

+4
source share
2 answers

I did some research for this subject, since your problem was very interesting. It seems better to use prop () instead of attr (). http://ejohn.org/blog/jquery-16-and-attr/

Also this post may be useful for you: jQuery, Chrome and "selected" attribute anomalies

  $('select[multiple] option').mousedown(function(e){ var self = $(this); e.preventDefault(); console.log(self.attr('selected')); if ( self.is(':selected')) self.prop('selected', false); else self.prop('selected', 'selected'); }); 

Here is a working example I tried in chrome: http://jsfiddle.net/7sZUj/ Hope this helps you.

+3
source

OK, since IE is disconnected from the table, try the following: http://jsfiddle.net/Udf5c/5/

 $('select[multiple] option').mousedown(function(e){ var sel = $(this).parent('select'); var opt = $(this); var pushTarget = false; var selectedOptions = sel.find('option:selected'); if (opt.attr('selected')) { selectedOptions = $($.grep(selectedOptions, function(val) { return $(val).val() != opt.val(); })); } else { selectedOptions.push(opt); } sel.children().each(function() { $(this).attr('selected', false); }); selectedOptions.each(function() { var o = sel.find('option[value="' + $(this).val() + '"]'); o.attr('selected', 'selected'); }); e.preventDefault(); }); 

It checks what has just been selected, then deselects and reselects the ones you want. :)

0
source

All Articles