2010-04-16 107 views
9

我試過四處尋找,但也有類似的問題,但我的方式更簡單,但是,我找不到這些內部的解決方案論壇。jQuery:顯示從選擇下拉列表中的元素,當選擇其他選項時隱藏它

在學習jQuery時,我試圖在選擇下拉列表中的某個項目/選項時顯示DIV,並在選擇下拉列表中的任何其他選項時隱藏相同的DIV。

選擇HTML:

<select name="source" id="source"> 
    <option value="null" selected="selected">&mdash;Select&mdash;</option> 
    <option value="s1">Source 1</option> 
    <option value="s2">Source 2</option> 
    <option value="sother">Other</option> 
</select> 

DIV我需要在 '其他' 選擇顯示:

<div id="specify-source">Other source here...</div> 

當選擇在選擇菜單中的任何其他選項,上面的DIV不應該可見。

我已經試過這jQuery的,但當然,它不能正常工作:

$(function() { 
$.viewMap = { 
    'sother' : $('#specify-source') 
    };  
    $('#source').change(function() { 
    // hide all 
    $.each($.viewMap, function() { this.hide(); }); 
    // show current 
    $.viewMap[$(this).val()].show(); 
    }); 
}); 

任何幫助,您可以給我,我會非常感激。

感謝,

回答

20

我看到你試圖與查看地圖做一個選擇。以簡化IT:

$('#source').change(function() { 
    ($(this).val() == "sother") ? $('#specify-source').show() : $('#specify-source').hide(); 
}); 
+0

由於我是新來stackoverflow.com我不能投票,但這個答案馬上工作。 非常感謝阿米特,非常感謝。 感謝其他人的幫助。 – 2010-04-19 19:57:32

+0

完成,我現在能夠投票:) – 2010-04-22 18:39:26

+0

嘿,謝謝你回來。 – Amit 2010-04-24 23:02:13

0

這是隱藏元素最簡單的方法:

$('.target').hide(); 

這裏是顯示和隱藏的jQuery的例子:

<!DOCTYPE html> 
<html> 
<head> 
<style> 
div { background:#def3ca; margin:3px; width:80px; 
display:none; float:left; text-align:center; } 
</style> 
<script src="http://code.jquery.com/jquery-latest.js"></script> 
</head> 
<body> 

<button id="showr">Show</button> 
<button id="hidr">Hide</button> 
<div>Hello 3,</div> 

<div>how</div> 
<div>are</div> 
<div>you?</div> 
<script> 
$("#showr").click(function() { 
$("div:eq(0)").show("fast", function() { 
/* use callee so don't have to name the function */ 
$(this).next("div").show("fast", arguments.callee); 
}); 
}); 
$("#hidr").click(function() { 
$("div").hide(2000); 
}); 

</script> 
</body> 
</html> 
0

simplier:

$(function() { 
$("#specify-source").hide(); 

$("#source").change(function(){ 
    if ($(this).val() == "sother") 
     $("#specify-source").show(); 
    else 
     $("#specify-source").hide(); 
    }); 
}); 
0

忽略你的視圖m ap,在這裏你去:

$("#source").change(function() { 
    var foo = false; 
    $("#source option:selected").each(function() { if ($(this).val() == "sother") foo = true; }); 
    if (foo) $('#specify-source').show(); else $('#specify-source').hide(); 
}).change(); 

你想我包括如何與所有的代碼?

其他發佈方式也能發揮作用,但不會工作,但不會處理與@多個=「多」

0

我忘了提及的是,DIV我需要的時候選擇了「其他」選項,需要在進入頁面被隱藏顯示,所以我增加了.hide();屬性。

我還加了一個slideDown('fast');幫助可用性。

這是我的最終代碼感謝Amit的幫助:

$('#specify-source').hide(); 
$('#source').change(function() { 
($(this).val() == "sother") ? 
$('#specify-source').slideDown('fast') : $('#specify-source').hide(); 
}); 
相關問題