下拉列表 - 单击选项时显示div

时间:2012-05-13 13:09:05

标签: javascript html5

您必须编写一个功能,根据用户选择的内容“显示”表单的相应部分。例如,如果选择“Pizza”,则应显示带有关于Pizza类型的问题的div#section2。

这是html代码的一部分

<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>

我如何编写一个javascript函数,以便当我单击选项pizza时,它会显示第2部分?我是一个完整的JavaScript新手,所以任何帮助都会很棒。

2 个答案:

答案 0 :(得分:3)

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";

}

查看演示。将section3section4 div替换为实际内容。

答案 1 :(得分:2)

有很多解决方案。最简单的选项之一是稍微更改标记并使用div ID。

HTML:

<div id="section1">
    <label for="food">What is your favourite type of food?</label>
    <select id="food" onchange="selection(this)">
        <option value="pizza">Pizza</option>
        <option value="mex">Mexican</option>
        <option value="thai">Thai</option>
    </select>
</div>
<div id="section_pizza" style="display: none;">
    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>

JavaScript的:

function selection(select) {
    document.getElementById("section_" + select.value).style.display = "block";
}

但是,您可以使用JQuery library并使其更快,更灵活。您可以轻松地向块添加动画并添加额外的功能。

HTML:

<div id="section1">
    <label for="food">What is your favourite type of food?</label>
    <select id="food">
        <option value="pizza">Pizza</option>
        <option value="mex">Mexican</option>
        <option value="thai">Thai</option>
    </select>
</div>
<div id="section2" data-type="pizza" style="display: none;">
    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>

JavaScript的:

$("#food").change(function() {
    $("[data-type]").hide();
    $("[data-type='" + this.value + "']").show(1000);
});