Eddie
Eddie

Reputation: 43

Second Select Menu Change Based On First Select Menu

I'm trying to build two select menu but the second result will based on the first selection. Both menu do not need to retrieve data from database. This web page requires two actions therefore I'm unable to perform it using PHP. The first action is onchange due to the first selection. The second action is to insert into database. From online, I read recommendation to do this is to build on javascript. Reading through others' post made me very confused as they were different in a sense.

What I want to achieve: If someone selected Acer in Brand, then only Model belonging to Acer should appeared. Same goes to Apple.

Acer Models: TravelMate, Extensa, Aspire
Apple Models: MacBook, MacBook Air, MacBook Pro

I'm not good in programming, so please bear with me. I have not insert any javascript or PHP in this coding.

My html codes shown as below:

          <tr>
        <td class="LABEL">Brand</td>
        <td><select name="Brand" class="LABEL" id="Brand">
          <option selected="selected">Brand</option>
          <option value="Acer">Acer</option>
          <option value="Apple">Apple</option>
      </select></td>
      </tr>       
      <tr>
        <td class="LABEL">Model</td>
        <td><select name="Model" class="LABEL" id="Model">
          <option selected="selected">Model</option>

          <option value="TravelMate">TravelMate</option>
          <option value="Extensa">Extensa</option>
          <option value="Aspire">Aspire</option>

          <option value="MacBook">MacBook</option>
          <option value="MacBook Air">MacBook Air</option>
          <option value="MacBook Pro">MacBook Pro</option>

        </select></td>
      </tr>

It would be great if you could help with me this. Thanks in advance.

Upvotes: 1

Views: 1030

Answers (1)

sinisake
sinisake

Reputation: 11328

Here is one possible solution. I've changed your HTML, so options are created dinamicaly (better solution, if you want to add more brands and models later).

Acer_models=new Array('TravelMate','Extensa','Aspire');
Apple_models=new Array('MacBook', 'MacBook Air', 'MacBook Pro');


function show_models(){

    brand=document.getElementById('Brand');
model=document.getElementById('Model');
 model.options.length = 1;
 selected=brand.options[brand.selectedIndex].value;
    if(selected=="Acer") {
        arr=Acer_models;
    }
    else if(selected=="Apple") {
        arr=Apple_models;
    }

    for(i=0;i<arr.length;i++) {
var option = document.createElement("option");
option.text = arr[i];
model.add(option);
        }







}

Here is jsfiddle: http://jsfiddle.net/4w8zaywg/

P.S. Line model.options.length=1, will assure that only 'model' option is present on change event...

Upvotes: 2

Related Questions