Prototype - How to deselect the selected value from a dropdown

19,212

Solution 1

I found the following code worked well:

var options = $$('select#mylist option');
var len = options.length;
for (var i = 0; i < len; i++) {
  options[i].selected = false;
}

Solution 2

I'm not sure how to do it in prototype, but I can do it in JavaScript.

For a regular select, set yourSelectElement.selectedIndex = -1.

For a multiple select, you can just ctrl+click on the selected item, but you can do it programmatically as well. See link.

http://jsfiddle.net/kaleb/WxJ9R/

Solution 3

You can't : you'll have to add an empty option

<option></option> 

and then

$$("#mylist option[selected]")[0].selected = false;
$$("#mylist option")[0].selected = true;

Solution 4

On the event of the second list being selected...

Event.observe('secondlist', 'change', function(){
  if (this.selectedIndex >= 0) 
    $$('#mylist option[selected]').invoke('writeAttribute', 'selected', false);
});
Share:
19,212
woot586
Author by

woot586

Updated on June 09, 2022

Comments

  • woot586
    woot586 about 2 years

    How do I deselect the selected value from a dropdown list using Prototype.

    From

    <select id=“mylist” MULTIPLE >
    <option value=“val-1”>Value 1</option>
    <option value=“val-2” SELECTED>Value 2</option>
    <option value=“val-3”>Value 3</option>
    </select>
    

    To

    <select id=“mylist” MULTIPLE >
    <option value=“val-1”>Value 1</option>
    <option value=“val-2”>Value 2</option>
    <option value=“val-3”>Value 3</option>
    </select>
    

    Thanks for any help in advance.

  • kzh
    kzh about 13 years
    That's exactly what was in my fiddle.
  • gordon
    gordon about 11 years
    jQuery also does not do this as well - at least in the limited looking I have done. Both $("#mySelect").val(null) and $("#mySelect").prop("selected",null) turn the highlight off but do not actually remove the selected property from a select-one. My validation believes mySelect has a selection and allows submit, even though it appears nothing is selected.