Created
March 31, 2012 19:41
-
-
Save robcowie/2267793 to your computer and use it in GitHub Desktop.
Filter option elements by optgroup based on value of a second select element
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$.fn.filterGroups = function( options ) { | |
var settings = $.extend( {}, options); | |
return this.each(function(){ | |
var $select = $(this); | |
// Clone the optgroups to data, then remove them from dom | |
$select.data('fg-original-groups', $select.find('optgroup').clone()).children('optgroup').remove(); | |
$(settings.groupSelector).change(function(){ | |
var $this = $(this); | |
var optgroup_label = $this.val().toUpperCase(); | |
var $optgroup = $select.data('fg-original-groups').filter('optgroup[label=' + optgroup_label + ']').clone(); | |
$select.children('optgroup').remove(); | |
$select.append($optgroup); | |
}).change(); | |
}); | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> | |
</head> | |
<body> | |
<div> | |
<select name="test1" id="test1"> | |
<option value="abc">abc</option> | |
<option value="def" selected="selected">def</option> | |
<option value="ghi">ghi</option> | |
<option value="jkl">jkl</option> | |
</select> | |
<select name="test2" id="test2"> | |
<optgroup label="abc"> | |
<option value="skldjaskld">asdasd</option> | |
<option value="skldjaskld">adasd</option> | |
<option value="skldjaskld">asdasdasdas</option> | |
</optgroup> | |
<optgroup label="def"> | |
<option value="skldjaskld">;'wdjq;iwljq</option> | |
<option value="skldjaskld">ljkhlduaskjdh als</option> | |
<option value="skldjaskld">sjkldhakjs dkasd</option> | |
</optgroup> | |
<optgroup label="ghi"> | |
<option value="skldjaskld">wqe</option> | |
<option value="skldjaskld">weqwew</option> | |
</optgroup> | |
<optgroup label="jkl"> | |
<option value="skldjaskld">weqwe</option> | |
<option value="skldjaskld">wwww</option> | |
</optgroup> | |
</select> | |
</div> | |
</body> | |
<script> | |
$(function() { | |
$('#test2').filterGroups({groupSelector: '#test1', }); | |
}); | |
</script> | |
</html> |
Thanks 👍
It save me the time to write it myself, as said above, works nicely if you remove the toUpperCase
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice, thank you! Please remove the "toUpperCase()" - it prevents your code from working...