Select2 Usage Summary

Select2 Usage Summary

introduce

Select2 is a jQuery based replacement for select boxes. It supports searching, remote data sets, and infinite scrolling of results.

Location

Dropdown box multiple selection box

function

Single choice multiple choice search custom style

premise

jQuery

Use

Edition

  • jQuery v3.3.1
  • Select2 v4.0.5
<link rel="stylesheet" type="text/css" href="https://cdn.bootcss.com/select2/4.0.5/css/select2.min.css">
<script type="text/javascript" src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.bootcss.com/select2/4.0.5/js/select2.min.js"></script>

function

Initialization

<select id="initialize">
		<option>Beijing</option>
		<option>Shanghai</option>
		<option>Guangzhou</option>
		<option>Shenzhen</option>
	</select>
$("#initialize").select2({});

Modify width

<select id="editWidth">
	<option>Beijing</option>
	<option>Shanghai</option>
	<option>Guangzhou</option>
	<option>Shenzhen</option>
</select>
$("#editWidth").select2({
	width:"300px"
});

Multiple selection

<select id="multiple" multiple="multiple">
		<option>Beijing</option>
		<option>Shanghai</option>
		<option>Guangzhou</option>
		<option>Shenzhen</option>
	</select>
$("#multiple").select2({
				width:"300px"
			});

placeholder

<select id="placeholder" multiple="multiple">
		<option>Beijing</option>
		<option>Shanghai</option>
		<option>Guangzhou</option>
		<option>Shenzhen</option>
	</select>
$("#placeholder").select2({
				width:"300px",
				placeholder:"Select an option"
			});

Custom selection style

<link rel="stylesheet" type="text/css" href="https://cdn.bootcss.com/font-awesome/4.7.0/css/font-awesome.min.css">
<select id="customSelect">
		<option>Beijing</option>
		<option>Shanghai</option>
		<option>Guangzhou</option>
		<option>Shenzhen</option>
	</select>
$("#customSelect").select2({
				width:"300px",
				templateResult:function(state){
					console.log(state);
					if(!state.id){
						return state.text;
					}
					var $state=$(
						'<span>'+state.text+'<i class="fa fa-square-o" style="float:right;"></i></span>'
						);
					return $state;
				}
			});

Custom style before and after selection

<select id="customSelect" multiple="multiple">
		<option>Beijing</option>
		<option>Shanghai</option>
		<option>Guangzhou</option>
		<option>Shenzhen</option>
	</select>
$("#customSelect").select2({
				width:"300px",
				templateResult:function(state){
					console.log(state);
					if(!state.id){
						return state.text;
					}
					var $state;
					if(state.selected==true){
						$state=$(
							'<span>'+state.text+'<i class="fa fa-check-square-o" style="float:right;"></i></span>'
							);
					}else{
						$state=$(
							'<span>'+state.text+'<i class="fa fa-square-o" style="float:right;"></i></span>'
							);
					}
					return $state;
				}
			});

Tags: JQuery Javascript

Posted on Wed, 06 Nov 2019 13:19:47 -0800 by eddiegster