0

I have a multiple choice option menu (I can select multiple elements from the list using command/shift/etc). I want all of the options to be selected as a default (when the page loads). I know that I can use

$(document).ready() 

to wait until the page loads to perform an action, but I don't know how to actually change the selected state of the list. Note that there are not checkboxes.

The HTML for the options looks like this:

<select name="name" id="id1">
    <option value='value1'>
    <option value='value2'>
    <option value='value3'>
    <option value='value4'>
</select>

Note: I want the changes to be in the javascript rather than the HTML, as I am using a default 'multiple choice menu' template that is consistent across form fields, and I only want the one specific field to have everything selected by default. How can I do this?

  • 1
    you should provide more code so we can help you. – Gabriel Mesquita Aug 29 '17 at 18:13
  • I added HTML for clarification of how the multiple option list is created. – user7518095 Aug 29 '17 at 18:15
  • 1
    Have you you done any searching or made an attempt? Try looking at the jQuery documentation or see if https://stackoverflow.com/q/13332484/691711 helps. – zero298 Aug 29 '17 at 18:18
  • https://stackoverflow.com/questions/78932/how-do-i-programmatically-set-the-value-of-a-select-box-element-using-javascript – Alessi 42 Aug 29 '17 at 18:19
  • The difference is that in mine, the options are dynamic. I want all options to be selected, regardless of what options happen to be displayed when the page renders. The above posts give guidance as for what to do when the options are static. – user7518095 Aug 29 '17 at 18:26

1 Answers1

2

By default, a <select> element is only configured to have one option shown at a time. So in order to select multiple elements at the same time, you'll need to set the <select> element's multiple attribute to true. You can do this with JavaScript like so:

document.getElementById('id1').multiple = true;

Once you do that, you can programmatically "select" each option. Here is a working example:

var el = document.getElementById('id1');

el.multiple = true;

for (var i = 0; i < el.childNodes.length; i++) {
  el.childNodes[i].selected = true;
}
<select name="name" id="id1">
    <option value='value1'>1</option>
    <option value='value2'>2</option>
    <option value='value3'>3</option>
    <option value='value4'>4</option>
</select>
freginold
  • 3,946
  • 3
  • 13
  • 28