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
515 views
in Technique[技术] by (71.8m points)

javascript - Deselect selected options in select menu with multiple and optgroups

I want to be able to with a click of a link to be able to deselect all pre-selected options in a select menu with multiple select enable and with option groups.

Here is an example of the menu:

<select name="ddBusinessCategory" id="ddBusinessCategory" class="f1" style="width:280px;height:200px" multiple="multiple">
<option value="">Select One</option>
<optgroup label="Abrasives" style="background:#F5F5F5;border-bottom:1px #EEE solid">
<option value="4" selected="selected">Abrasives</option>
</optgroup>
<optgroup label="Abstracters" style="background:#F5F5F5;border-bottom:1px #EEE solid">
<option value="5">Abstracters</option>
</optgroup>
<optgroup label="Abuse Information &amp; Treatment Centers" style="background:#F5F5F5;border-bottom:1px #EEE solid">
<option value="6" selected="selected">Abuse Information &amp; Treatment Centers</option>
</optgroup>
<optgroup label="Accountants" style="background:#F5F5F5;border-bottom:1px #EEE solid">
<option value="7">Accountants</option>
<option value="2672">Certified Public Accountants - </option>
<option value="2673">Public Accountants - </option>
</optgroup>
<optgroup label="Accounting Services" style="background:#F5F5F5;border-bottom:1px #EEE solid">
<option value="8">Accounting Services</option>
</optgroup>
<optgroup label="Acoustical Materials - Wholesale &amp; Manufacturers" style="background:#F5F5F5;border-bottom:1px #EEE solid">
<option value="9">Acoustical Materials - Wholesale &amp; Manufacturers</option>
</optgroup>
</select>

You will see two are selected.. I want to be able to deselect these preselected ones.

DONT want to use jquery, just want to use javascript

Many thanks for your assistance.

neojakey

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The following function should loop through all the options and unselect them.

HTML

<a href="#" onclick="clearSelected();">clear</a>

JAVASCRIPT

 function clearSelected(){
    var elements = document.getElementById("ddBusinessCategory").options;

    for(var i = 0; i < elements.length; i++){
      elements[i].selected = false;
    }
  }

EDIT:

I don't endorse putting the event handler directly on the element. If you have the option, give the element some type of id/name and bind the event handler in your JavaScript code.

EXAMPLE


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

...