jQuery – Syncing select options

I had a requirement for a series of select boxes that required the related one to only allow selections above the first. I created a little utility function that enables and disables the options based on a function you supply.  Usage is pretty simple. Pass in the first and second select as jQuery objects, then pass in your function that evaluates whether an option is enabled or not.

This simple example disables any values in the PriceTo that are below the value in PriceFrom:

1
2
3
4
SelectSync($('#PriceFrom'),$('#PriceTo'), function(a,b){
	//Check that a is less than b
	return parseInt(a.val()) < parseInt(b.val());
});

 The SelectFilter routine

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function SelectFilter(Source, Dest, process) {
	Source.change(function(e) {
		var item = Source.find('option:selected');
		var first = true;
		Dest.find('option').each(function(i) {
			if (process($(this), item)) {
				$(this).attr('disabled', 'disabled');
			} else {
				$(this).removeAttr('disabled');
				if (first) {
					$(this).attr('selected', 'selected');
					first = false;
				}
			}
		});
	});
}

Leave a Reply

Your email address will not be published. Required fields are marked *