html - How to toggle selection of an option in a multi-select with jQuery? -
i have standard select multiple
html input field, example:
<select multiple="multiple" size="5" id="mysel" name="countries"> <option value="2">afghanistan</option> <option value="4">aland</option> </select>
as multi-select, select more 1 value have hold ctrl key , select further elements. want achieve is, that:
- clicking unselected option selects it
- clicking selected option unselects it.
the idea avoid having press ctrl key , change usage semantics of input field. elements should selectable , un-selectable clicking (ie. toggling of select status).
i have not yet been able implement this. pseudo-code should this.
- catch click event.
- check if element clicked unselected, select it
- or if element clicked selected, unselect it.
how should implement this?
you may use following snippet achieve 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, prop()
not available:
$("select[multiple] option").mousedown(function(){ var $self = $(this); if ($self.attr("selected")) $self.attr("selected", ""); else $self.attr("selected", "selected"); return false; });
Comments
Post a Comment