2015-05-15 109 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(); 
     } 
    }); 
}); 
相关问题