Come posso trasformare un elemento select in una lista con jQuery?

Come posso trasformare un elemento select in una lista con jQuery?

jQuery ci permette di domare graficamente anche le select box, notoriamente ostiche da formattare con i CSS.

Dato un elemento select così strutturato:


<select name="choice" id="choice" data-title="Scegli">
	<option value="A">A</option>
	<option value="B">B</option>
	<option value="C">C</option>
</select>

la soluzione è la seguente:


(function( $ ) {
	$.fn.select = function() {
		return this.each(function() {
			var $element = $( this ),
				html = "<ul class='select-list'>";
			
			    html += "<li><span>" + $element.data( "title" ) + "</span></li>";
			    
			    $element.find( "option" ).each(function() {
				   html += "<li data-value='" + $( this ).val() + "'>" + $( this ).text() + "</li>"; 
				    
			    });
			    
			    html += "</ul>";
			    
			    $element.hide().before( html );
			    
			    $element.prev().
			    find( "> li" ).not( "li:first" ).each(function() {
				   var $item = $( this );
				   var value = $item.data( "value" );
				   $item.click(function() {
					  $element.val( value );
					  $element.prev().toggleClass( "open" );
					  $element.prev().find( "span" ).addClass( "item-selected" ).text( $item.text() ); 
				   });
				 
			    });
		});
	};

	
})( jQuery );

Il plugin crea la lista nascondendo al contempo la select box. Ad ogni click su una voce della lista verrà impostato il corrispondente valore per la select box.

Torna su