Skip to content

Instantly share code, notes, and snippets.

@hopbit
Forked from anonymous/jsbin.kuneg.html
Last active August 29, 2015 14:02
Show Gist options
  • Save hopbit/6a7c03afc6c55813673e to your computer and use it in GitHub Desktop.
Save hopbit/6a7c03afc6c55813673e to your computer and use it in GitHub Desktop.
attach unselect behaviour to multibox, original source: http://jsbin.com/kuneg/1/edit, after modifications: http://jsbin.com/kuneg/15/edit
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<select size="10" multiple id="myMultiSelectBox">
<option value="1" selected>One</option>
<option value="2" selected>Two</option>
<option value="3" selected>Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
<option value="6" selected>Six</option>
<option value="7">Seven</option>
<option value="8">Eight</option>
<option value="9">Nine</option>
</select>
<script>
attachUnselectBehaviour($("#myMultiSelectBox"));
function attachUnselectBehaviour(selectBoxObj) {
var selected = {};
// initialize with previously selected values
var selectedValues = selectBoxObj.val();
var arrayLength = selectedValues.length;
for (var i = 0; i < arrayLength; i++) {
selected[selectedValues[i]] = true;
}
// console.log(selected);
selectBoxObj.click(function(e) {
var $this = $(this),
options = this.options,
option,
value,
n;
// Find out what option was just added
value = $this.val();
// Re-apply the selections
for (n = 0; n < options.length; ++n) {
option = options[n];
if (option.value == value) {
// The one being updated
selected[value] = !selected[value];
}
// One of the others
option.selected = !!selected[option.value];
}
return false;
});
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment