eff
eff

Reputation: 11

Change options value in a drop-down list depending on another selected drop-down list

I have problem to change the value of the options from the code below, select which changes depending on other select, but I want to change the value of the select id = "numbList", thanks ....

<!DOCTYPE html>
<html>
<body>   

<select id="diffList" onchange="changeList()"> 
  <option value="">-- Difficulty --</option> 
  <option value="1">Easy</option> 
  <option value="2">Medium</option> 
  <option value="3">Difficult</option> 
</select> 

<select id="numbList"></select> 

<script>
window.difficulty = {};
window.difficulty['1'] = [1,2,3];
window.difficulty['2'] = [4,5,6];
window.difficulty['3'] = [7,8,9];

function changeList() {
    var diffList = document.getElementById("diffList");
    var numbRange = document.getElementById("numbList");
    var selectDiff = diffList.options[diffList.selectedIndex].value;
    while(numbRange.options.length)
    {
        numbRange.remove(0);
    }
    var diff = window.difficulty[selectDiff];
    if(diff)
    {
        var i;
        for(i = 0; i < diff.length; i++)
        {
            var difficulty = new Option(diff[i], i);
            numbRange.options.add(difficulty);
        }
    }
}
</script>

</body>
</html>

Upvotes: 1

Views: 104

Answers (1)

mollwe
mollwe

Reputation: 2275

Just use diff[i] for both text and value for option:

...
for(i = 0; i < diff.length; i++)
{
    var value = diff[i];
    var difficulty = new Option(value, value);
    numbRange.options.add(difficulty);
}
...

As the previous value is removed from select options it selects the first of the new options. So you shouldn't need to set the value of numbList.

To set value of numbList programmatically you could just do numbList.value = 1; for example.

Upvotes: 1

Related Questions