[英]Button to clear text and reset search input not working
好的,所以我有一個可過濾的搜索表單,它返回網格中的某些圖像,效果很好,當我刪除搜索輸入中的文本時它會重置,但是當我點擊“清除”按鈕時,它應該做同樣的事情刪除文本,它不起作用。 這是使用的 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 = "";
});
});
任何幫助將不勝感激。
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 實例作為別名。 這樣您仍然可以在該函數的范圍內安全地使用$
變量。
由於接受的答案不能解決問題。
嘗試input
事件而不是keyup
$("#filter").on("input", function() {.....
& 然后清除您想要的事件的過濾器輸入字段。
$(".clear-btn").on("click", function() {
$("#filter").val("").trigger("input");
});
將此添加到您的 CSS:
input[type="search"]::-webkit-search-cancel-button { -webkit-appearance: searchfield-cancel-button; }
<form> <input type="search" name="search" placeholder="Search..."> </form>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.