Add selected attribute to parameter in selection menu using jQuery

I am creating a plugin for the selected menu to replace the ugly default selections and be consistent across OSs.

Here's a demo (firefox and webkit only)
http://spacirdesigns.com/selectMenu/

It already works, but I'm having trouble assigning the "selected" attribute. The code works with any other attribute, but I cannot get it to work with the selected attribute.

It works:

select.find('option') .removeAttr('whatever') .eq(index).attr('whatever', 'hello'); 

It does not mean:

 select.find('option') .removeAttr('selected') .eq(index).attr('selected', 'selected'); 

And here is the code so far:

 (function($){ $.fn.selectMenu = function() { var select = this; select.hide(); var title = select.attr('title'); var arrow = 'img/arrow.png'; var items = ''; select .children('option') .each(function(){ var item = $(this).text(); if ($(this).val() != '') { $(this).attr('value', item); } items += '<li>' + item + '</li>' }); var menuHtml = '<ul class="selectMenu">' + '<img src="' + arrow + '" alt=""/>' + '<li>' + title + '</li>' + '<ul>' + items + '</ul>' + '</ul>'; select.after(menuHtml); var menu = $(this).next('ul'); var list = menu.find('ul'); menu .hover(function(){}, function(){ list.hide(); }) .children('li').hover(function(){ list.show(); }); menu.find('ul li').click(function(){ var index = $(this).index(); menu.children('li').text($(this).text()); select.find('option') .removeAttr('selected') .eq(index).attr('selected', 'selected'); list.hide(); }); }; })(jQuery); 
+7
source share
3 answers

Check out this previous detailed answer to SO :

If you really want to output HTML output with the selected attribute and not only have jQuery that types the correct selectedIndex attribute on the select element, you can crack the original settAttr () function:

 select[0].options[select[0].selectedIndex].setAttribute('selected','selected'); 

But as soon as you continue to use the jQuery methods for val () or ': selected', you should not have a problem, you can have a problem only if you parsed HTML to find the selected attribute, something should not do, never.

+3
source

As with jQuery 1.6 "To get and change DOM properties, such as checked, selected, or disabled state of form elements, use the .prop () method."

 $("#someselect option[value=somevalue]").prop("selected", "selected") 
+23
source

Given your last comment, I assume your problem is firebug, not your code. Why this works with attributes other than "selected" is that choosing an option from the drop-down menu does not change the selected attribute in the DOM. I assure you there is nothing wrong with the code.

0
source

All Articles