基本上,我尝试在更改选择时更改输入的文本和占位符。但是,它不起作用,我不确定它为什么没有。
<select class="form-control" name="search_type" id="search_type" style="width: 80%">
<option selected id="item_name" value="item_name">Item Name</option>
<option id="item_creator" value="item_creator">Item Creator</option>
</select>
<input type="text" id="search" name="search" placeholder="Item Name..." maxlength="50" class="form-control" style="width: 100%">
<script>
$(document).ready(function() {
function search() {
$('#search').text('');
$('#search').attr("placeholder", "Item Name...");
if($("#search_type option:selected") == "item_name") {
$('#search').text('');
$('#search').attr("placeholder", "Item Name...");
} else if($("#search_type option:selected") == "item_creator") {
$('#search').text('');
$('#search').attr("placeholder", "Creator Name...");
}
}
$("#search_type").change(search);
});
</script>
先谢谢
答案 0 :(得分:1)
主要问题是$("#search_type option:selected")
将返回DOM元素的jquery对象。所以你无法将它与字符串进行比较..
使用$("#search_type").val()
测试所选值。更好的是,因为方法的上下文是select
元素,您可以直接使用this.value
。
您还可以简化方法(,因为您重复了很多部分)
function search() {
val searchEl = $('#search').val('').prop("placeholder", "Item Name..."),
value = this.value;
if(value == "item_name") {
searchEl.prop("placeholder", "Item Name...");
} else if(value == "item_creator") {
searchEl.prop("placeholder", "Creator Name...");
}
}
答案 1 :(得分:1)
您的问题在于您是如何尝试获取选择的值:
if($("#search_type option:selected") == "item_name") {
应该是:
if($("#search_type").val() == "item_name") {
在下面的代码片段中,我还减少了代码,因此您不会通过在jQuery查询的结果中设置变量来反复查询相同的内容。
另外,我利用了jQuery的“方法链”,而不是:
$('#search').text('');
$('#search').attr("placeholder", "Item Name...");
你可以写:
$('#search').text('').attr("placeholder", "Item Name...");
$(document).ready(function() {
var $txt = $("#txtSearch");
var $searchType = $("#search_type");
function search() {
$txt.text('').attr("placeholder", "Item Name...");
if($searchType.val() === "item_name") {
$txt.text('').attr("placeholder", "Item Name...");
} else if($searchType.val() === "item_creator") {
$txt.text('').attr("placeholder", "Creator Name...");
}
}
$searchType.change(search);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" id="txtSearch" name="search" placeholder="Item Name..." maxlength="50" class="form-control" style="width: 100%">
<select class="form-control" name="search_type" id="search_type" style="width: 80%">
<option selected id="item_name" value="item_name">Item Name</option>
<option id="item_creator" value="item_creator">Item Creator</option>
</select>