jquery select option sort


Adalah suatu hal yang mudah untuk mengurutkan value dan isi dari sebuah option di server sebelum ditampilkan di browser. Tapi bagaimana jika kita ingin melakukannya menggunakan JavaScript?


Untuk kebutuhan sort ini, kita bisa menggunakan algoritma merge sort dari literateprograms.org.

( function ($) {
	
	$.fn.selectOptionSort = function(options) {
		
		// set default options
		var defaults = {
			orderBy: "text",	// text or value
			sort: "asc"			// asc or desc
		}; 
	
		// extend the default to options
		options = $.extend(defaults, options);
		
		return this.each( function() {
			
			// populate array element
			// we need the 0 element as sort value
			var content = new Array();
			
			if (options.orderBy == "value") {
				$(this).children().each( function() {
					var valueText = [
						$(this).val(),
						$(this).text()
					];
					
					content.push(valueText);
				});
			}
			else {
				$(this).children().each( function() {
					var valueText = [
						$(this).text(),
						$(this).val()						
					];
					content.push(valueText);
				});
			}
						
			// sort populated array
			if (options.sort == "desc") {
				var sorted = merge_sort(content, desc);
			}
			else {
				var sorted = merge_sort(content, asc);
			}
			
			// empty the select object
			$(this).empty();
			
			// append element to the select object
			if (options.orderBy == "value") {
				for (var i = 0; i < sorted.length; i++) {
					$(this).append(
						$("<option></option>")
							.val(sorted[i][0])
							.text(sorted[i][1])
					);
				}
			}
			else {
				for (var i = 0; i < sorted.length; i++) {
					$(this).append(
						$("<option></option>")
							.text(sorted[i][0])
							.val(sorted[i][1])
					);
				}
			}
		});
		
	};
	
	// callback ascending sort
	var asc = function(left, right) {
		
		if (left[0] == right[0]) {
			return 0;
		}
		else if (left[0] < right[0]) {
			return -1;
		}
		else {
			return 1;
		}
	};
	
	// callback descending sort
	var desc = function(left, right) {
		
		if (left[0] == right[0]) {
			return 0;
		}
		else if (left[0] < right[0]) {
			return 1;
		}
		else {
			return -1;
		}
	};
	
	// merge array
	var merge = function (left,right,comparison) {
		var result = new Array();
		
		while((left.length > 0) && (right.length > 0)) {
			if(comparison(left[0],right[0]) <= 0) {
				result.push(left.shift());
			}					
			else {
				result.push(right.shift());
			}	
		}
		
		while(left.length > 0) {
			result.push(left.shift());
		}
		
		while(right.length > 0) {
			result.push(right.shift());
		}
			
		return result;
	};
	
	// sort and/or merge array
	var merge_sort = function(array,comparison) {
		if(array.length < 2) {
			return array;
		}
		
		var middle = Math.ceil(array.length/2);
		
		return merge(merge_sort(array.slice(0,middle),comparison),
				merge_sort(array.slice(middle),comparison),
				comparison);
	};
	
})(jQuery);

Contoh penggunaannya

<span class="textAsc">TEXT ASC</span>
<br>
<span class="valueAsc">VALUE ASC</span>
<br>
<span class="textDesc">TEXT DESC</span>
<br>
<span class="valueDesc">VALUE DESC</span>
<br>
<select name="country" id="country" multiple size="11">
    <option value="BRN">Brunei</option>
    <option value="KHM">Cambodia</option>
    <option value="IDN">Indonesia</option>
    <option value="LAO">Laos</option>
    <option value="MYS">Malaysia</option>
    <option value="MMR">Myanmar</option>
    <option value="PHL">Philippines</option>
    <option value="SGP">Singapore</option>     
    <option value="THA">Thailand</option>
    <option value="TLS">Timor-Leste</option>
    <option value="VNM">Vietnam</option>
</select>
$(function () {

	$(".textAsc").click( function() {
		$("#country").selectOptionSort({
			orderBy: "text",
			sort: "asc"
		});
	});

	$(".textDesc").click( function() {
		$("#country").selectOptionSort({
			orderBy: "text",
			sort: "desc"
		});
	});

	$(".valueAsc").click( function() {
		$("#country").selectOptionSort({
			orderBy: "value",
			sort: "asc"
		});
	});

	$(".valueDesc").click( function() {
		$("#country").selectOptionSort({
			orderBy: "value",
			sort: "desc"
		});
	});

});

live demo jsFiddle

source code terbaru bisa dilihat di:

direct link:

Tinggalkan Balasan

Isikan data di bawah atau klik salah satu ikon untuk log in:

Logo WordPress.com

You are commenting using your WordPress.com account. Logout / Ubah )

Gambar Twitter

You are commenting using your Twitter account. Logout / Ubah )

Foto Facebook

You are commenting using your Facebook account. Logout / Ubah )

Foto Google+

You are commenting using your Google+ account. Logout / Ubah )

Connecting to %s

%d blogger menyukai ini: