Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear all selected items in a SELECT input using jQuery?

I am think this should be fairly easy, but struggling a bit ... I have a SELECT input element that allows the user to select multiple items. I would like to provide a mechanism for them to clear all selected items, probably will just be a SPAN tag or something similar.

Anyway ... using jQuery, how I would I clear the selection on the SELECT input element so no items are selected.

like image 727
mattruma Avatar asked Jan 20 '11 14:01

mattruma


People also ask

How do I remove dynamically selected options in jQuery?

Approach: Select the option from select which needs to remove. Use JQuery remove() method to remove the option from the HTML document.

How do I unselect a selected option?

You can deselect any cells within the selected range with the Deselect Tool. Pressing the Ctrl key, you can click, or click-and-drag to deselect any cells or ranges within a selection. If you need to reselect any of those cells, continue holding the Ctrl key and reselect those cells (for Mac, use the Cmd key).

How do you remove all options from select in jQuery except first?

Explanation: If we want to remove all items from dropdown except the first item then we can use $('#ddlItems option:not(:first)'). remove(); Here we have excluded first item from being deleted. If we want to remove all items from dropdown except the last item then we can use $('#ddlItems option:not(:last)').

How do you clear a selection in HTML?

To remove the options of an HTML element of select , you can utilize the remove() method: function removeOptions(selectElement) { var i, L = selectElement.


2 Answers

In the case of a <select multiple> the .val() function takes/returns an array, so you can simply pass in an empty array to clear the selection, like this:

$("#selectID").val([]); 

You can test it out here.

like image 157
Nick Craver Avatar answered Oct 14 '22 11:10

Nick Craver


This worked to clear all selected options for me..

$("#selectListName").prop('selectedIndex', -1) 

The select list looked like

<select multiple='multiple' id='selectListName'>    <option>1</option>    <option>2</option>    <option>3</option>    <option>4</option> </select> 
like image 34
roblem Avatar answered Oct 14 '22 11:10

roblem