2015-05-15 189 views
3

我有一個下拉選擇框並輸入文本框。選擇框中顯示我的類別和它的外觀像這樣:根據Jquery中的下拉選擇框填充輸入文本框

<select id="category" name="category"> 
    <option value="">Please select...</option> 
    <option value="1">Category-1</option> 
    <option value="2">Category-2</option> 
    <option value="3">Category-3</option> 
    <option value="4">Other</option> 
</select> 

輸入文本框是這樣的:

<input type="text" id="otherCategory" name="otherCategory" value="" style="display: none;"> 

我的問題是。當用戶從下拉菜單中選擇「其他」時,我需要填充輸入文本。

我想它是這樣的:

$(document).ready(function() { 

    $('#category').change(function() { 
     var myValue = $(this).val(); 
     var myText = $("#category :selected").text(); 

     if (myText != '' AND myText == "Other") { 
      $("#otherCategory").show(); 
     } 
    }); 
}); 

但我無法得到它的工作。任何人都可以告訴我如何解決這個問題。

注意:我的下拉列表選擇動態填充。

謝謝。

+1

將您的AND替換爲&& – stanze

回答

6

您在if條件缺&&。此外,您的條件

myText != ''是多餘的,不是必需的。

當選擇發生變化時,您需要隱藏input

$(document).ready(function() { 

    $('#category').on('change', function() { 
     var myValue = $(this).val(); 
     var myText = $.trim($("#category :selected").text()).toLowerCase(); // Trim spaces and convert to lowercase for comparison 

     $("#otherCategory").toggle(myText === 'other'); 
    }); 
}); 

演示:https://jsfiddle.net/tusharj/8ykfmtyt/1/

4

您需要使用&&代替AND

Live Demo

if (myText != '' && myText === "Other") { 
    $("#otherCategory").show(); 
} 

您可以通過與其他選項,然後 '其他' 的selcted躲在進一步優化。 當您將其與字符串'other'進行比較時,您不需要檢查它是否爲空,因此我從if語句中刪除了該條件。

Live Demo

$('#category').change(function() { 
     $(this).find(":selected").text() === "Other" ? 
     $("#otherCategory").show() : $("#otherCategory").hide(); 
}); 
+0

謝謝。 「==」和「===」運算符有什麼不同? – user3733831

+0

==類型轉換和===將值與類型進行比較 – Tushar

+1

@ user3733831 1'== 1'爲'true',而'1'=== 1'爲'false' ',因爲一個是'integer',另一個是'string' – Tushar

2

嘗試此Demo,如果用戶選擇表示隱藏別的輸入領域的其他選項。

$(document).ready(function() { 

    $('#category').change(function() { 
     var myValue = $(this).val(); 
     var myText = $("#category :selected").text(); 

     if (myText == "Other") { 
      $("#otherCategory").show(); 
     } 
     else{ 
      $("#otherCategory").hide(); 
     } 
    }); 
}); 
相關問題