Manipulating Select Boxes
jQuery Novice to Ninja 8.3
by beej
HTML
<form>
<select id="candidates" multiple="multiple" size="8">
<option value="1">Beau Dandy</option>
<option value="2">Johnny Stardust</option>
</select>
<select id="a-listers" multiple="multiple" size="8">
</select>
<div id="controls">
Swap:
<input type="button" id="swapLeft" value=">" />
<input type="button" id="swapRight" value="<" /><br />
Swap All:
<input type="button" id="swapAllLeft" value=">>" />
<input type="button" id="swapAllRight" value="<<" /><br />
<input type="button" id="invert" value="Invert" /><br />
Search: <input type="text" id="searchBox" size="25" />
</div>
</form>
CSS
select {
min-width: 100px;
}
input[type=button] {
min-width: 35px;
}
JavaScript
var SWAPLIST = {};
SWAPLIST.swap = function(from, to) {
$(from).find(':selected').appendTo(to);
};
SWAPLIST.swapAll = function(from, to) {
$(from).children().appendTo(to);
};
SWAPLIST.invert = function(list) {
$(list).children().attr('selected', function(i, selected) {
return !selected;
});
};
SWAPLIST.search = function(list, search) {
$(list).children().attr('selected', '').filter(function() {
if (search === '') {
return false;
}
return $(this).text().toLowerCase().indexOf(search) > - 1;
}).attr('selected', 'selected');
};
$("#swapLeft").click(function() {
SWAPLIST.swap("#candidates", "#a-listers");
});
$("#swapRight").click(function() {
SWAPLIST.swap("#a-listers", "#candidates");
});
$("#swapAllLeft").click(function() {
SWAPLIST.swapAll("#candidates", "#a-listers");
});
$("#swapAllRight").click(function() {
SWAPLIST.swapAll("#a-listers", "#candidates");
});
$("#invert").click(function() {
SWAPLIST.invert("#candidates, #a-listers");
});
$("form").on("submit", function(event) {
event.preventDefault();
});
$("#searchBox").keyup(function() {
SWAPLIST.search("#a-listers, #candidates", $(this).val());
});