BruceyBandit
BruceyBandit

Reputation: 4324

Dropdown values I do not want to display using javascript

I have two dropdown menus.

1st -> Drop Down Menu (name="DropDown1") has 2 values which are ABC and ABCD
2nd -> Drop Down Menu (name="DropDown2") has 3 values which are 1, 2 and 3.

Now my question is that in Javascript if the user selects ABC from DropDown1, then how can I get it so that DropDown2 only shows values 1 and 2 only and not 3, this is because you can't pick 3 answers for ABC, but then be able to show values 1, 2 and 3 in DropDown2 if user selects ABCD from DropDown1.

Thank You

Upvotes: 0

Views: 218

Answers (2)

mprabhat
mprabhat

Reputation: 20323

You have to have two Arrays and on selection of question you have to populate options in Answer select, Sample Code:

<html>
    <head>
    <title>Question Answer Test</title>
    <script type="text/javascript">
        var dropdown1 = [];
        var dropdown2 = [];

        dropdown1[0] = new Option("1", "1");
        dropdown1[1] = new Option("2", "2");

        dropdown2[0] = new Option("1", "1");
        dropdown2[1] = new Option("2", "2");
        dropdown2[2] = new Option("3", "3");

        function populateAnswer(qusSelectBox, ansSelectBox){
            var tempMenuItem;
            ansSelectBox.options.length = 0;

            switch (qusSelectBox.selectedIndex) {
                case 0:
                    tempMenuItem = dropdown1;
                    break;
                case 1:
                    tempMenuItem = dropdown2;
                    break;
           }

           for (var i = 0; i < tempMenuItem.length; i++) {
                ansSelectBox.options[i] = tempMenuItem[i];
           }
   }

    </script>
    </head>
    <body>
        <form name="Menus">
            <select name="Question" onchange="populateAnswer(this, this.form.Answer);">
                 <option value="ABC">ABC</option>
                 <option value="ABCD">ABCD</option>
            </select> 
            <select name="Answer">
                <option value="1">1</option>
                <option value="2">2</option>
            </select>
        </form>
    </body>
 </html>

Upvotes: 1

BZink
BZink

Reputation: 7947

I would set up an object of key/value pairs that hold your selection possibilities. Then bind to the change event on DropDown1 so that you rewrite the options of DropDown2 when it changes.

Your javascript object would look something like this...

var DropOne = new Array();

DropOne.ABC = [1, 2];
DropOne.ABCD = [1, 2, 3];

If you add the jQuery tag to the question I'd happily show you some working code. I couldn't do it in pure javascript off the top of my head though... whoops :)

Alright... well here it is with jQuery if you want it...

http://jsfiddle.net/brettzink/pND9u/

Upvotes: 1

Related Questions