列表框值更改时隐藏div

时间:2014-03-24 19:37:35

标签: javascript css html listbox

好的我有4个div,我想在列表框的值与div id相同时显示它们 抱歉,这可能是一个令人讨厌的问题,但我是JavaScript的新手 这是针对日历条目的重复活动页面。

例如

<select name="Repeat" id="Repeat">
    <option value="Never">Never</option>
    <option value="Daily">Daily</option>
    <option value="Weekly">Weekly</option>
    <option value="Monthly">Monthly</option>
    <option value="Yearly">Yearly</option>
  </select>

<div id="Daily" if selected in listbox "repeat" make this div visible else hide>
daily events
</div>

<div id="Weekly" if selected in listbox "repeat" make this div visible else hide>
weekly events
</div>

<div id="Monthly" if selected in listbox "repeat" make this div visible else hide>
monthly events
</div>

<div id="Yearly" if selected in listbox "repeat" make this div visible else hide>
yearly events
</div>

2 个答案:

答案 0 :(得分:0)

你可以很容易地使用jQuery做到这一点。只需使用.change()事件。

$(document).ready(function(){

    $("#Repeat").change(function(){

        $("div").fadeOut();
        $("#"+$(this).val()).fadeIn();

    });

});

JSFiddle


如果您需要使用纯Javascript执行此操作,则可以执行onChange事件:

<强> HTML:

<select ... onchange="hideShow()">

<强> JS:

function hideShow()
{
    document.getElementById("Daily").style.display = "none";   
    document.getElementById("Weekly").style.display = "none";   
    document.getElementById("Monthly").style.display = "none";   
    document.getElementById("Yearly").style.display = "none";   

    document.getElementById(document.getElementById("Repeat").value).style.display = "block";   
}

JSFiddle

答案 1 :(得分:0)

如果你只想使用普通的javascript: 1.将onchange添加到选择

<select name="Repeat" id="Repeat" onchange="changeRepeat(this.value)">

,功能应该是这样的:

function changeRepeat(value){
  if(value == "Never"){
    document.getElementById('Daily').style.display = "none";
    document.getElementById('Weekly').style.display = "none";
    document.getElementById('Monthly').style.display = "none";
    document.getElementById('Yearly').style.display = "none";
    //document.getElementById('Yearly').style.display = "block"; to show
  }
  //else if value == daily, weekly...
}