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:

  1. clicking unselected option selects it
  2. 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.

  1. catch click event.
  2. check if element clicked unselected, select it
  3. 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

Popular posts from this blog

c++ - Convert big endian to little endian when reading from a binary file -

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -

unicode - Are email addresses allowed to contain non-alphanumeric characters? -