Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
756 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...