user3565412
user3565412

Reputation: 91

javascript: changing "multiple" attribute of the "select" element does not work

Windows 7 64 bit, Chrome version 61.0.3163.100

I have a html page with a listbox:

<select id='lst' multiple>...</select>

I need to disable multiple items selection for this listbox. I have a javascript function with this code:

lst = document.getElementById('lst');
lst.multipe = false;

I have checked in the debugger - the value changed to "false". But in another function called "onclick", it is "true" again. And multiple items could be selected with [shift] or [ctrl] pressed.

Upvotes: 2

Views: 3451

Answers (2)

Robby Cornelissen
Robby Cornelissen

Reputation: 97150

The multiple attribute is a boolean attribute, and, according to the HTML specification:

The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.

Use removeAttribute() instead:

const element = document.getElementById('select');
element.removeAttribute('multiple');
<select id="select" multiple>
  <option>One</option>
  <option>Two</option>
  <option>Three</option>
</select>

Upvotes: 3

onalbi
onalbi

Reputation: 2759

lst = document.getElementById('lst');
lst.removeAttribute('multiple');
lst.setAttribute('multiple', true);
<select id='lst' multiple>
<option>1</option>
<option>2</option>
</select>

Multiple is based on presence, so you need to remove or set it if need from javascript.

Upvotes: 3

Related Questions