javascript 根据Jquery中的下拉选择框填充输入文本框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30253085/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Populate input text box based on drop down select box in Jquery
提问by user3733831
I have a drop down select box and input text box. Select box display my categories and its look like this:
我有一个下拉选择框和输入文本框。选择框显示我的类别,它看起来像这样:
<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 text box is like this:
输入文本框是这样的:
<input type="text" id="otherCategory" name="otherCategory" value="" style="display: none;">
My question is. when an user select only "Other" from dropdown then I need to populate the input text.
我的问题是。当用户从下拉列表中仅选择“其他”时,我需要填充输入文本。
I tried it something like this:
我试过这样的事情:
$(document).ready(function() {
$('#category').change(function() {
var myValue = $(this).val();
var myText = $("#category :selected").text();
if (myText != '' AND myText == "Other") {
$("#otherCategory").show();
}
});
});
But I couldn't get it to work. Can anybody tell how I figure this out.
但我无法让它工作。谁能告诉我是如何解决这个问题的。
NOTE: my dropdown select populating dynamically.
注意:我的下拉选择动态填充。
Thank you.
谢谢你。
回答by Tushar
You are missing &&
in if
condition. Also, your condition
你缺少&&
的if
条件。还有你的情况
myText != ''
is redundant and not required.
myText != ''
是多余的,不是必需的。
And you need to hide the input
when selection changed.
并且您需要隐藏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');
});
});
回答by Adil
You need to use &&
instead of AND
你需要使用&&
而不是AND
if (myText != '' && myText === "Other") {
$("#otherCategory").show();
}
You can further optimize it by hiding with option other then 'other' is selcted. You do not need to check if it is not empty when you are comparing it with string 'other' so I removed that condition from if statement.
您可以通过使用其他选项隐藏来进一步优化它,然后选择“其他”。当您将它与字符串 'other' 进行比较时,您不需要检查它是否不为空,因此我从 if 语句中删除了该条件。
$('#category').change(function () {
$(this).find(":selected").text() === "Other" ?
$("#otherCategory").show() : $("#otherCategory").hide();
});
回答by stanze
Try this Demo, if user selects other option showing input field else hiding.
试试这个Demo,如果用户选择其他选项显示输入字段其他隐藏。
$(document).ready(function() {
$('#category').change(function() {
var myValue = $(this).val();
var myText = $("#category :selected").text();
if (myText == "Other") {
$("#otherCategory").show();
}
else{
$("#otherCategory").hide();
}
});
});