Skip to content

Instantly share code, notes, and snippets.

@robcowie
Created March 31, 2012 19:41
Show Gist options
  • Save robcowie/2267793 to your computer and use it in GitHub Desktop.
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
$.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();
});
};
<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>
@geri777
Copy link

geri777 commented Mar 23, 2015

Nice, thank you! Please remove the "toUpperCase()" - it prevents your code from working...

@Argurth
Copy link

Argurth commented Oct 29, 2016

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