好的,所以我有一个可过滤的搜索表单,它返回网格中的某些图像,效果很好,当我删除搜索输入中的文本时会重置,但是当我单击“清除”按钮时,应该执行删除文本同样的事情,它不起作用。这是使用的HTML和JQuery:
<form id="live-search" action="" class="styled" method="post" style="margin: 2em 0;">
<div class="form-group">
<input type="text" class="form-control" id="filter" value="" style="width: 80%; float: left;" placeholder="Type to search"/>
<span id="filter-count"></span>
<input type="button" class="clear-btn" value="Clear" style="background: transparent; border: 2px solid #af2332; color: #af2332; padding: 5px 15px; border-radius: 3px; font-size: 18px; height: 34px;">
</div>
</form>
这是清算文本的JQuery:
jQuery(document).ready(function(){
jQuery("#filter").keyup(function(){
// Retrieve the input field text and reset the count to zero
var filter = jQuery(this).val(), count = 0;
// Loop through the comment list
jQuery(".watcheroo").each(function(){
jQuery(this).removeClass('active');
// If the list item does not contain the text phrase fade it out
if (jQuery(this).text().search(new RegExp(filter, "i")) < 0) {
jQuery(this).fadeOut();
// Show the list item if the phrase matches and increase the count by 1
} else {
jQuery(this).show();
count++;
}
});
// Update the count
var numberItems = count;
});
//clear button remove text
jQuery(".clear-btn").click( function() {
jQuery("#filter").value = "";
});
});
非常感谢任何帮助。
答案 0 :(得分:3)
value
是DOMElement上的属性,而不是jQuery对象。请改用val('')
:
jQuery(document).ready(function($) {
$("#filter").keyup(function() {
var filter = $(this).val(),
count = 0;
$(".watcheroo").each(function(){
var $watcheroo = $(this);
$watcheroo.removeClass('active');
if ($watcheroo.text().search(new RegExp(filter, "i")) < 0) {
$watcheroo.fadeOut();
} else {
$watcheroo.show();
count++;
}
});
var numberItems = count;
});
$(".clear-btn").click(function() {
$("#filter").val(''); // <-- note val() here
});
});
请注意,我将您的代码修改为别名传递给document.ready处理程序的jQuery实例。这样,您仍然可以在该函数的范围内安全地使用$
变量。
答案 1 :(得分:1)
因为接受的答案不能解决问题。
尝试input
事件而不是keyup
$("#filter").on("input", function() {.....
&,然后清除所需事件的过滤器输入字段。
$(".clear-btn").on("click", function() {
$("#filter").val("").trigger("input");
});
答案 2 :(得分:0)
将此添加到CSS:
input[type="search"]::-webkit-search-cancel-button {
-webkit-appearance: searchfield-cancel-button;
}
<form>
<input type="search" name="search" placeholder="Search...">
</form>