BWSnippet

jQuery CSS styled select multiple

jQuery CSS styled select multiple

Use a list styled anyway you want to be used as a multiple select form element using jQuery.

I have run into this situation a few times. I basically want a form with a multi-select element but I want it to look a particular way. It is not easy to style a multi-select form element in most browsers. So one workaround is to use jQuery and a regular HTML list. Add some basic jQuery functionality and there ya go.

Styles


		.tagList {
			margin: 0px;
		}
		.tagList .selected{
			background-color: rgba(33,240,0,0.49);
			border: solid #fb00ff 2px;	
		}
		.tagList li{
			border: solid #9d9d9d 2px;	
			border-radius: 0px;
			padding: 5px;
			margin: 5px;
		}

		.tagList{
			width: 200px;
			border: solid #6c7281 1px;
			overflow: scroll;
			max-height: 250px;
		}

HTML


			<select multiple="multiple" id="multiListForTags">
			
			</select>
			
			<ul class="tagList">
				<li data-tag-id="1">thing</li>
				<li data-tag-id="2">stuff</li>
				<li data-tag-id="3">yup</li>
				<li data-tag-id="4">hi</li>
				<li data-tag-id="5">it</li>
				<li data-tag-id="6">that</li>
				<li data-tag-id="7">hmmm</li>
				<li data-tag-id="8">another thing</li>
			</ul>
			
			<a id="submit" class="btn">Fake Submit</a>

jQuery



				$('.tagList').on('click', 'li' , function(e) {
					if( $(this).hasClass('selected') )
						$(this).removeClass('selected') 
					else
						$(this).addClass('selected') 
				});
				
					
				$('#submit').click(function(){
					
					
					$('#multiListForTags').text("");
					$('.tagList li').each(function(){					
						if( $(this).hasClass('selected') )
						{
							
							$('#multiListForTags').append("<option selected='selected' value=\"" + $(this).attr("data-tag-id") + "\">" + $(this).text() + "</option>");
						}
					});
					
				});

Tags

jQuery CSS styled select multiple