Skip to content

Instantly share code, notes, and snippets.

Created June 11, 2014 12:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save anonymous/ca429a3da0b66faf55e3 to your computer and use it in GitHub Desktop.
Save anonymous/ca429a3da0b66faf55e3 to your computer and use it in GitHub Desktop.
<!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 selectedValues = selectBoxObj.val();
var arrayLength = selectedValues.length;
var selected = {};
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