Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
328 views
in Technique[技术] by (71.8m points)

html - How to toggle selection of an option in a multi-select with jQuery?

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:

  1. Clicking an UNSELECTED option SELECTs it
  2. Clicking a SELECTED option UNSELECTS it.

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.

  1. Catch a Click event.
  2. Check if the element that was clicked was unselected, then select it
  3. Or if the element that was clicked was selected, then unselect it.

How should I implement this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...