I have a standard select multiple
HTML Input field, for example:
<select multiple="multiple" size="5" id="mysel" name="countries">
<option value="2">Afghanistan</option>
<option value="4">Aland</option>
</select>
As this is a multi-select, to select more than one value you have to hold the CTRL key and select any further elements. However what I want to achieve is, that:
The idea is to avoid having to press the CTRL key and change the usage semantics of this input field. Elements should only be selectable and un-selectable by clicking (ie. toggling of the select status).
I have not yet been able to implement this. The pseudo-code should look something like this.
How should I implement this?
With jQuery, you can use the . val() method to get an array of the selected values on a multi-select dropdown list.
For windows: Hold down the control (ctrl) button to select multiple options. For Mac: Hold down the command button to select multiple options.
Allow users to select multiple items from a list. Each item is rendered as a tag with an icon to remove the value.
You may use the following snippet to achieve your desired effect
$("select[multiple] option").mousedown(function(){
var $self = $(this);
if ($self.prop("selected"))
$self.prop("selected", false);
else
$self.prop("selected", true);
return false;
});
In older versions of jQuery, where prop()
was not available:
$("select[multiple] option").mousedown(function(){
var $self = $(this);
if ($self.attr("selected"))
$self.attr("selected", "");
else
$self.attr("selected", "selected");
return false;
});
Javascript (without jquery):
var select = document.getElementById('mysel');
select.addEventListener('mousedown', function(e){
var opt = e.target;
if (opt.selected){
opt.removeAttribute('selected');
opt.selected = false;
} else {
opt.setAttribute('selected', '');
opt.selected = true;
}
e.preventDefault();
});
I see most of the answers above are binding the event with the option instead of the select. If my select has 1000 options, then it will bind 1000 events, will it affect the performance?
Because of this I also decide not to bind my event in the option.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With