【问题标题】:Show different elements of a form depending on dropdown box selection根据下拉框选择显示表单的不同元素
【发布时间】:2012-07-10 18:30:22
【问题描述】:

所以我有一个包含下拉列表和表单的页面。我想要做的是取决于在下拉列表中选择的选项,我想隐藏和显示表单的不同部分。

<select id="myselect>
    <option id="option1">Option_1</option>
    <option id="option2">Option_2</option>
    <option id="option3">Option_3</option>
</select>

<form action="" method="post">
    <input id="input_1" name="input_1" type="text" />
    <input id="input_2" name="input_2" type="text" />
    <input id="input_3" name="input_3" type="text" />
</form>

因此,如果选择了 Option_1,则显示 input_1 和 input_3,同时隐藏 input_2

【问题讨论】:

  • 确保在 id="myselect" 上也有一个尾随"

标签: javascript html forms


【解决方案1】:

纯 JS

window.onload=function() {
  document.getElementById("myselect").onchange=function() {
    document.getElementById("input_2").style.display=(this.options[this.selectedIndex].value=="option1")?"none":"block";
  }
  document.getElementById("myselect").onchange(); //trigger
}

【讨论】:

    【解决方案2】:

    我设法通过在您的选项标签中添加“值”属性来解决您的问题:

    <select id="myselect">
        <option id="option1" value="option1">Option_1</option>
        <option id="option2" value="option2">Option_2</option>
        <option id="option3" value="option3">Option_3</option>
    </select>
    
    <form action="" method="post">
        <input id="input_1" name="input_1" type="text" placeholder="input_1"/>
        <input id="input_2" name="input_2" type="text" placeholder="input_2"/>
        <input id="input_3" name="input_3" type="text" placeholder="input_3"/>
    </form>​
    

    并使用 jquery .change() 事件:

    $select = $('#myselect');
    $('#input_2').hide();
    $('#input_3').hide(); 
    
    
    $select.change(function(){
        if($(this).val() == "option1"){
            if($('#input_1').is(":hidden")){
                $('#input_1').show();            
            }        
            $('#input_2').hide();
            $('#input_3').hide(); 
        }
        if($(this).val() == "option2"){
            if($('#input_2').is(":hidden")){
                $('#input_2').show();            
            }
            $('#input_1').hide();
            $('#input_3').hide(); 
        }
        if($(this).val() == "option3"){
            if($('#input_3').is(":hidden")){
                $('#input_3').show();            
            }
            $('#input_1').hide();
            $('#input_2').hide(); 
        }     
    });​
    

    jsfiddle

    【讨论】:

    • 可能不是您想要的,因为我只是重读了您的问题。当您选择 option_1 时,您希望同时显示 input_1 和 input_3?在那种情况下,我失败了。
    猜你喜欢
    • 2012-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-20
    • 1970-01-01
    相关资源
    最近更新 更多