Marcelo Marcelo - 6 months ago 28
Javascript Question

Conditional simple drop down list?

I'm trying to program a website using HTML and I have a question. I'm using a drop-down list with options A and B, but after one of this is chosen, I'd like to create another drop down list and text fields at the same page, with different questions. For example, If some one choose A, then it'll be asked questions C and D, and if someone chose B, it'll be asked questions E and F. What is the best way to program this ?

Sorry for any mistake in English, I'm not a native speaker.
And Thanks in advance.


It depends on whether the data is static (i.e. coded on the page and will not change) or dynamic (i.e. delivered from the web server).

If your drop-down lists are supposed to only filter their contents based on List A, then you will probably want to use some JavaScript to hide / remove the items that you don't want. Consider looking at jQuery for this as it's an extremely easy to use and understand framework and there are plenty of good examples both on Stack Overflow and throughout the Internet that you can refer to.

If your data needs to be delivered from a web server (i.e. you have a database that you're referring to for the list values) then you'll need to provide more information about your programming framework (e.g. ASP.Net, PHP, etc) and how you want the lists to work (Ajax, full-page postback, etc).

Let's assume you're keeping everything static on the page and hiding information based on the user's selection.

Your HTML might look something like this:

    <div id="myQuestions">
        <select id="QuestionOptions">
            <option value="A">Question A</option>
            <option value="B">Question B</option>
    <div id="myAnswers">
        <div id="A" style="display: none;">
            <div id="QuestionC">
                <p>Here is an example question C.</p>
            <div id="QuestionD">
                <select id="QuestionOptionsD">
                    <option value="G">Question G</option>
                    <option value="H">Question H</option>
        <div id="B" style="display: none;">
            <div id="QuestionE">
                <p>Here is an example question E.</p>
            <div id="QuestionF">
                <select id="QuestionOptionsF">
                    <option value="I">Question I</option>
                    <option value="J">Question J</option>

Your JavaScript (I'm using jQuery, as mentioned above) could then look like this:

$(function () {
    $('#QuestionOptions').change(function () {
        $('#myAnswers > div').hide();
        $('#myAnswers').find('#' + $(this).val()).show();