2009-06-25 146 views
5

我的代碼:如何顯示/隱藏的div(jQuery的)

<select id="select"> 
<option id="1" value="thai language">option one</option> 
<option id="2" value="eng language">option two</option> 
<option id="3" value="other language">option three</option> 
</select> 

<div id="form1">content here</div> 
<div id="form2">content here</div> 
<div id="form3">content here</div> 

我想是顯示DIV#form1的時候選擇選項1,隱藏窗口2 + form3,或 選擇選項2顯示div#form2並隱藏form1 + form2

回答

15
$('#select').change(function() { 
    $('#form1, #form2, #form3').hide(); 
    $('#form' + $(this).find('option:selected').attr('id')).show(); 
}); 

請注意,ID不應該以數字開頭,但上面應該這樣做。

+1

沿着我在想什麼線。 $(this).attr('id')不會引用select本身的id?我想我必須得到選擇索引,抓住這個選項,然後得到ID。 – Sampson 2009-06-25 11:00:11

0

像這樣的東西?

var optionValue = $("#select").val(); 

$('#form1, #form2, #form3').hide(); 

switch(optionValue) 
{ 
case 1: 
    $("#form1").show(); 
    break; 
case 2: 
    $("#form2").show(); 
    break; 
case: 3: 
    $("#form3").show(); 
    break; 
} 
0

只隱藏以前顯示的div不是更好嗎? 所以;

var selection = 0; 
$('#select').change(function() { 
    $('#form' + selection).hide(); 
    selection = $(this).val(); 
    $('#form' + selection).show(); 
}); 

請注意,ID不應以數字開頭,但上面應該這樣做。

2

如果您的形式是大的,你可以把他們在這樣單獨的文件,

$(document).ready(function() { 
    $('#select').change(function() { 
     $("#myform").load(this.value); 
    }); 
}); 


<select id="select"> 
<option value="blank.htm">Select A Form</option> 
<option value="test1.htm">option one</option> 
<option value="test2.htm">option two</option> 
<option value="test3.htm">option three</option> 
</select> 

<div id="myform" ></div> 
0

更好的版本:

$('#select').change(function() { 
    $('div').not('#form' + $(this).find('option:selected').attr('id')).hide(); 
    $('#form' + $(this).find('option:selected').attr('id')).show(); 
});