2014-04-03 54 views
0

我試圖在某個選項菜單上的某個選項被點擊時顯示一段文字和一個文本框。類似的代碼適用於單選按鈕,但在這種情況下似乎沒有。我真的很感激任何幫助,我可以得到這一點。 jsfiddle無法在jQuery中選擇下拉菜單項以顯示隱藏文本框

HTML:

<select name="select1"> 
<option value="doctor" id="doctor1">Doctor</option> 
<option value="nurse" id="nurse1">Nurse</option> 
<option value="other" id="other1">Other</option> 
</select> 
<div class="otherprof"> 
<p>Please list your profession: 
<input type="text" name="otherproftext" id="otherproftext" maxlength="20"> 
</p> 
</div> 

的jQuery:

$(document).ready(function() { 
$(".otherprof").hide(); 
$("#other1").click(function() { 
    $(".otherprof").show(); 
}); 
$("#doctor1").click(function() { 
    $(".otherprof").hide(); 
}); 
$("#nurse1").click(function() { 
    $(".otherprof").hide(); 
}); 
}); 

的想法是,該文本框保持隱藏,直到用戶在「其他」點擊下拉菜單,這反過來應該顯示的文本框立即。

回答

1

您需要在select上使用onchange事件,而不是單擊選項。

$("[name='select1']").on("change", function(){  //listen for change event on the select 
    $(".otherprof").toggle(this.value==="other"); //toggle show/hide based on selected value 
}).change(); //trigger the change event so default value is checked 

JSFiddle

+1

你打我的答案,但這裏有一個[工作演示(HTTP:/ /jsfiddle.net/hN63N/1/)在JSFiddle上。 :) –

+0

很好地工作,謝謝。我想知道爲什麼jQuery不會讓你在這種情況下使用.click。無論如何,只要stackoverflow讓我接受你的答案。 – user3361043

+0

@ user3361043它不是jQuery,大多數瀏覽器中的選項都沒有點擊事件。 – epascarello

-1

樣式屬性添加到div otherprof,它最初將隱藏

<select name="select1"> 
    <option value="doctor" id="doctor1">Doctor</option> 
    <option value="nurse" id="nurse1">Nurse</option> 
    <option value="other" id="other1">Other</option> 
</select> 
<div class="otherprof" style="display:none;"> 
<p>Please list your profession: 
    <input type="text" name="otherproftext" id="otherproftext" maxlength="20"> 
</p> 
</div> 
相關問題