tipsywacky tipsywacky - 1 year ago 76
HTML Question

html: How to add default options in multiple select tags?

I have 8 select tags in one html page. Here is one of them.

<select id="list1" name="cat1">
<option value="0">Select Option</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>

If I got some random default values that need to be preset to the options like
<option selected="selected">
. Let's say a default list = [2,5,6,4,3,6,8,9]. How would anyone approach to this problem most efficiently?

Any jquery functions set the default option values? Thanks in advance.

Answer Source

You can't choose more than one option in a <select> unless you give the the multiple attribute:

<select id="list1" name="cat1" multiple>
    <option selected>Some selected option</option>
    <option>Not selected</option>
    <option selected>This is also selectedoption>

This way, you can give multiple <option>s the selected attribute.

If you need to select multiple values provided from an array in JS, you can do:

[2, 5, 6, 4, 3, 6, 8, 9].forEach(function(valToSelect) {
  $( 'select#list1' ).find('option[value="' + valToSelect + '"]').prop('selected', true);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download