2010-02-22 56 views
1

我敢肯定,這是超級簡單,但我似乎無法想象我做錯了什麼,無論如何,我有一個「標題」選擇列表我的表單,我想顯示一個文本框,如果「其他」被選中。在選擇顯示文本框與jQuery的?

<select name="title" id="title" class="required"> 
    <option value="" selected="selected">- Select Title -</option> 
    <option value="Ms.">Ms.</option> 
    <option value="Mrs.">Mrs.</option> 
    <option value="Mr.">Mr.</option> 
    <option value="Dr.">Dr.</option> 
    <option value="Prof.">Prof.</option> 
    <option value="Rev.">Rev.</option> 
    <option value="Other" onclick="showOther();">Other</option> 
</select> 

function showOther() { 
    jQuery("#otherTitle").show(); 
} 

但是,這不工作.. #otherTitle文本框隱藏使用jquery當頁面加載。

+0

謝謝大家:) – SoulieBaby 2010-02-22 23:49:33

回答

1
  1. 使用jQuery綁定你的事件處理程序,而不是「onfoo」元素的屬性
  2. 你最好結合的處理程序,以「選擇」的元素,因爲有辦法了該選項可以選擇,這將不涉及「點擊」事件:

(一些文本,使計算器顯示下面的代碼塊)

$(function() { 
    $('#title').change(function() { 
    if ($(this).val() == 'Other') 
     $('#otherTitle').show(); 
    else 
     $('#otherTitle').hide(); 
    }); 
}); 

我倒是PREF呃給「其他」選項一個「身份證」的價值,而不是依靠「價值」,但無論如何。

2

我會建議不同的方法:

$("#title").change(function() { 
    if($(this).find("option:last").is(':selected')) { 
     $("#otherTitle").show(); 
    } else { 
     $("#otherTitle").hide(); 
    } 
}); 

也就是說,如果選擇了最後選項,表明由ID otherTitle進入文本框。我實際上使用這種方法。希望有所幫助。當然,您的'其他'字段必須始終保持最後才能發揮作用 - 再加上它對於多語言網站來說非常方便。

1

綁定一個事件,您的選擇列表中,當它改變時,看價值,做你的隱藏/顯示

$(function(){ 

    $("#title").change(function() { 
     if ($(this).val() == 'Other') { 
      $("#otherTitle").show(); 
     } 
    }); 

}); 
1
$(function() {  
    $('#title').change(function() { 
     if (this.value === "Other") { 
     $("#otherTitle").show(); 
     } 
     else { 
     $("#otherTitle").hide(); 
     }  
    });  
}); 

Working Demo。添加/編輯到url看到代碼

相關問題