1

So I have a page that has a dropdown list and form. And what I want to do is depending on the option selected in the dropdown list I want to hide and show different parts of the form.

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

So if Option_1 is selected then show input_1 and input_3, while hiding input_2

4

2 回答 2

0

纯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
}
于 2012-07-09T05:53:08.587 回答
0

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

<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

于 2012-07-10T10:30:22.103 回答