Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
713 views
in Technique[技术] by (71.8m points)

javascript - Drop down list - display div when clicking an option

You must write a function that 'shows' the corresponding part of the form depending on what the user has selected. For example, if 'Pizza' is selected, the div #section2 with the question about Pizza type should be shown.

This is part of the html code

<form id="survey" action="#" method="post">

<div id="section1">
    <label for="food">What is your favourite type of food?</label>
    <select id="food" onchange="selection()">
        <option value="pizza">Pizza</option>
        <option value="mex">Mexican</option>
        <option value="thai">Thai</option>
    </select>
</div>
<div id="section2">
    What is your favourite type of pizza?<br>
    <label for="hawaiian">Hawaiian</label><input type="radio" id="hawaiian">
    <label for="supreme">Supreme</label><input type="radio" id="supreme">
    <label for="vegetarian">Vegetarian</label><input type="radio" id="vegetarian">
</div>

How would i write a javascript function so that when I click the option pizza, it will display section 2? I'm a complete javascript novice so any help would be great.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

DEMO: http://jsfiddle.net/iambriansreed/rQr6v/

JavaScript:

var sections = {
    'pizza': 'section2',
    'mex': 'section3',
    'thai': 'section4'   
};

var selection = function(select) {

    for(i in sections)
        document.getElementById(sections[i]).style.display = "none";    

    document.getElementById(sections[select.value]).style.display = "block";

}

Checkout the demo. Replace the section3 and section4 divs with actual content.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...