user2136922
user2136922

Reputation: 11

Javascript to populate an option box with an array

Hi was wondering if you could help, i need to use JavaScript to populate the clothes option box with appropriate options when the user specifies what type of gender they are. This is the code I have so far,

<script type="text/javascript">
var subListArray = [];
subListArray[0] = 'Select a type first';
subListArray[1] = ['skirt', 'dress', 'tights'];
subListArray[2] = ['jeans', 'hat'];
</script>

Person

       Gender Type: <select name="genderType" id="genderType" >
      <option value="">Gender Type?</option>
      <option value="girl">Female</option>
      <option value="boy">Male</option>
    </select> </br>

        Clothes <select name="clothType">
      <option value="">Choose a Type</option>
    </select>

Upvotes: 1

Views: 178

Answers (2)

Dave
Dave

Reputation: 46249

See this page which explains adding elements to the DOM: http://www.javascriptkit.com/javatutors/dom2.shtml

You need to use createElement, setAttribute and appendChild. E.g:

html:

<select id="mySelect">...</select>
<select id="mySubSelect"></select>

javascript:

var myNewOption = document.createElement( 'option' );
myNewOption.setAttribute( 'value', 'myOptionValue' );
document.getElementById( 'mySubSelect' ).appendChild( myNewOption );

This can go in a loop. Also you can detect when the selection changes like this:

javascript:

document.getElementById('mySelect').addEventListener('change',function(){
    document.getElementById('mySelect').selectedIndex; // a number showing which element is selected
});

With jQuery it is a lot easier.

Upvotes: 0

Explosion Pills
Explosion Pills

Reputation: 191729

Use objects instead of arrays so that you can map the subList to the selected gender. You don't have to do this, but it simplifies things a bit. Add a "change" listener to the gender selector that creates the option elements for the new select box:

var subListArray = {
    'default': ['Select a type first'],
    'girl': ['skirt', 'dress', 'tights'],
    'boy': ['jeans', 'hat'],
};

document.getElementById('genderType').addEventListener('change', function () {
    var sel = document.getElementById('clothType'),
        value = this.value ? this.value : 'default';
    sel.innerHTML = '';
    subListArray[value].forEach(function (item) {
       sel.appendChild(new Option(item));
    });
});

http://jsfiddle.net/VdXk6/

Upvotes: 1

Related Questions