Question

My function doesn't work at all and nothing happens in my second select. What I want is create options from an array in my second select depending on my selectedIndex in the first Select. Here's my code :

(I really don't understand what's going on, this code seems logically correct..)

<html>
    <head>
    <script>
        function Choix(form) {
            var x = form.Rubrique.selectedIndex;
            if (x == 0) {
                return;
            }
            switch (x) {
            case 1:
                var txt = new Array ('je','tets','esti');
                break;
            }
            case 2:
                var txt = new Array ('45','7575','47');
                break;
            }

            for (x=0;x<txt.length;i++) {
                var y = document.getElementById("Page");
                var option = document.createElement("option");
                option.text = txt[x+1];
                y.add(option);
            }
        } 
    </script>
    </head>
    <body>
    <form method="post" action="<?= $_SERVER['PHP_SELF'] ?>">
        <SELECT NAME="Rubrique" onChange='Choix(this.form)'>
<OPTION></OPTION>
<OPTION>Plongée</OPTION>
<OPTION>Nucléaire</OPTION>
<OPTION>Bonheur</OPTION>
</SELECT>

<SELECT NAME="Page" id="Page">
<OPTION></OPTION>
</SELECT>

    </body>
</html>
Was it helpful?

Solution

The function should look like this:

function Choix(form) {
  var x = form.Rubrique.selectedIndex;
  if (x == 0) {
    return;
  }
  switch (x) {
    case 1:
      var txt = new Array ('je','tets','esti');
      break;
    case 2:
      var txt = new Array ('45','7575','47');
      break;
  }

  var y = document.getElementById("Page");
  y.innerHTML = '<option></option>';
  for (x=0;x<txt.length;x++) {
    var option = document.createElement("option");
    option.text = txt[x+1];
    y.add(option);
  }
}

Every time you choose option in select1 you have to clear select2 from old values, that's why I wrote y.innerHTML = '<option></option>';

OTHER TIPS

Instead of:

y.add(option);

you have to do:

y.appendChild(option);

EDIT Also, your for has to be:

for (x=0; x < txt.length; x++)  //Counter increment was wrong

Cheers

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top