你如何检测清除“搜索”HTML5输入?

时间:2010-06-04 19:10:55

标签: javascript jquery events javascript-events html5

在HTML5中,search输入类型会在右侧显示一个小X,用于清除文本框(至少在Chrome中,可能是其他文件框)。有没有办法检测这个X在javascript或jQuery中被点击的时间,比如检测到什么时候单击该框或进行某种位置点击检测(x位置/ y位置)?

20 个答案:

答案 0 :(得分:87)

实际上,只要用户搜索或用户点击“x”,就会触发“搜索”事件。这特别有用,因为它理解“增量”属性。

现在,我已经说过,我不确定你是否可以区分点击“x”和搜索,除非你使用“onclick”黑客。无论哪种方式,希望这会有所帮助。

  

参考文献:

     

http://help.dottoro.com/ljdvxmhr.php

答案 1 :(得分:45)

绑定search - 在下面给出搜索框 -

$('input[type=search]').on('search', function () {
    // search logic here
    // this function will be executed on click of X (clear button)
});

答案 2 :(得分:37)

我想添加一个“迟到”的答案,因为我今天与changekeyupsearch进行了斗争,也许我最终找到的可能也对其他人有用。 基本上,我有一个类似搜索的面板,我只是想对小X的按下做出正确的反应(在Chrome和Opera下,FF没有实现它),结果清除内容窗格。

我有这段代码:

 $(some-input).keyup(function() { 
    // update panel
 }
 $(some-input).change(function() { 
    // update panel
 }
 $(some-input).on("search", function() { 
    // update panel
 }

(它们是分开的,因为我想检查每个人被调用的时间和条件)。

事实证明,Chrome和Firefox的反应不同。 特别是,Firefox将change视为“对输入的每次更改”,而Chrome将其视为“焦点丢失且内容更改时”。 因此,在Chrome上,“更新面板”功能被调用一次,在每次击键时两次调用FF(一个在keyup,一个在change

此外,使用小X(在FF下不存在)清除字段会在Chrome下触发search事件:否keyup,无change

结论?请改用input

 $(some-input).on("input", function() { 
    // update panel
 }

它在我测试的所有浏览器中都具有相同的行为,对输入内容的每次更改做出反应(包括鼠标复制粘贴,自动完成和“X”)。

答案 3 :(得分:14)

使用Pauan的回应,这几乎是可能的。实施例

<head>
    <script type="text/javascript">
        function OnSearch(input) {
            if(input.value == "") {
                alert("You either clicked the X or you searched for nothing.");
            }
            else {
                alert("You searched for " + input.value);
            }
        }
    </script>
</head>
<body>
    Please specify the text you want to find and press ENTER!
    <input type="search" name="search" onsearch="OnSearch(this)"/>
</body>

答案 4 :(得分:5)

对我而言,单击X应该算作更改事件。我已经将onChange事件设置为完成我需要它做的事情。所以对我来说,修复就是简单地执行这个jQuery行:

$('#search').click(function(){ $(this).change(); });

答案 5 :(得分:4)

您似乎无法在浏览器中访问此内容。搜索输入是Cocoa NSSearchField的Webkit HTML包装器。取消按钮似乎包含在浏览器客户端代码中,而包装器中没有可用的外部引用。

来源:

看起来你必须通过鼠标位置找出它,例如:

$('input[type=search]').bind('click', function(e) {
  var $earch = $(this);
  var offset = $earch.offset();

  if (e.pageX > offset.left + $earch.width() - 16) { // X button 16px wide?
    // your code here
  }
});

答案 6 :(得分:4)

2020-保持简单!

哇,对于一个非常简单的问题,这里有一些非常复杂的答案。

只需在您的搜索输入中添加'input'的侦听器,当用户在输入中输入内容或单击清除图标时,就会捕获该监听器。

document.getElementById('searchInput').addEventListener('input', (e) => {
  console.log(`Input value: "${e.currentTarget.value}"`);
})
<input id="searchInput" type="search" placeholder="Search" />

如果您不能使用ES6 +,则以下是您转换后的代码:

document.getElementById('searchInput').addEventListener('input', function(e) { 
  // Yay! You make it in here when a user types or clicks the clear icon
})` 

答案 7 :(得分:4)

我知道这是一个老问题,但我一直在寻找类似的东西。确定&#39; X&#39;单击以清除搜索框。这里没有任何答案对我有帮助。当用户点击“输入”时,其中一个很接近但也会受到影响。按钮,它会触发与单击&#39; X&#39;。

相同的结果

我在另一篇文章中找到了这个答案,它对我来说很完美,只有在用户清除搜索框时才会触发。

$("input").bind("mouseup", function(e){
   var $input = $(this),
   oldValue = $input.val();

   if (oldValue == "") return;

   // When this event is fired after clicking on the clear button
   // the value is not cleared yet. We have to wait for it.
   setTimeout(function(){
     var newValue = $input.val();

      if (newValue == ""){
         // capture the clear
         $input.trigger("cleared");
      }
    }, 1);
});

答案 8 :(得分:2)

最初的问题是“我可以检测到对 'x' 的点击吗?”。 这可以通过在 search 事件中“牺牲”Enter 来实现。

在输入框的生命周期中有许多事件在不同的时间触发 类型搜索:inputchangesearch。其中一些在某些情况下会重叠。默认情况下,当您按 Enter 和按 'x' 时会触发“搜索”;使用 incremental 属性,它也会在您添加/删除任何字符时触发,延迟 500 毫秒以捕获多个更改并避免使侦听器不堪重负。 问题是,search 会生成一个带有 input.value == "" 的模糊事件,因为它可能会以三种方式变为空:(1)“用户按下了 'x'”,(2)“用户在没有文本的输入上按下 Enter”,或 (3)“用户编辑输入(退格、剪切等)直到输入变为空,最终 incremental 触发了 search 事件空输入”。

消除歧义的最佳方法是将 Enter 排除在等式之外,并且仅在按下 'x' 时触发 search。您可以通过完全抑制 Enter 按键来实现这一点。我知道这听起来很愚蠢,但是您可以通过 keydown 事件(您也可以进行抑制)、input 事件或 {{1} } 事件。 change 唯一独特的是“x”点击。

如果您不使用 search,这将消除歧义。如果您使用 incremental,问题是,您可以使用 incremental 事件实现大部分 incremental 行为(您只需要重新实现 500 毫秒去抖动逻辑)。因此,如果您可以删除 input(或可选地用 incremental 模拟它),这个问题可以通过 inputsearchkeydown 的组合来回答。如果您不能去掉 event.preventDefault(),您将继续遇到上述的一些歧义。

这是一个演示这一点的代码片段:

incremental
inpEl = document.getElementById("inp");
monitor = document.getElementById("monitor");

function print(msg) {
  monitor.value += msg + "\n";
}

function searchEventCb(ev) {
  print(`You clicked the 'x'. Input value: "${ev.target.value}"`);
}

function keydownEventCb(ev) {
    if(ev.key == "Enter") {
    print(`Enter pressed, input value: "${ev.target.value}"`);
        ev.preventDefault();
    }
}

inpEl.addEventListener("search", searchEventCb, true);
inpEl.addEventListener("keydown", keydownEventCb, true);

在这个简单的代码段中,您将 <input type="search" id="inp" placeholder="Type something"> <textarea id="monitor" rows="10" cols="50"> </textarea> 变成了一个专用事件,该事件仅在您按“x”时触发,并回答最初发布的问题。您使用 search 跟踪 input.value 以回车。

就我个人而言,我更喜欢在按下 Enter 键时放一个 keydown(模拟输入框失去焦点),并监视 ev.target.blur() 事件以跟踪 change (而不是通过 input.value 监控 input.value)。通过这种方式,您可以统一跟踪 keydown 的焦点变化,这很有用。它对我有用,因为我只需要在 input.value 实际更改时才处理事件,但它可能不适用于所有人。

这是带有 input.value 行为的代码片段(现在,即使您手动将注意力从输入框移开,您也会收到一条消息,但请记住,只有在实际发生更改时才会看到更改消息):

blur()
inpEl = document.getElementById("inp");
monitor = document.getElementById("monitor");

function print(msg) {
  monitor.value += msg + "\n";
}

function searchEventCb(ev) {
  print(`You clicked the 'x'. Input value: "${ev.target.value}"`);
}

function changeEventCb(ev) {
  print(`Change fired, input value: "${ev.target.value}"`);
}

function keydownEventCb(ev) {
    if(ev.key == "Enter") {
        ev.target.blur();
        ev.preventDefault();
    }
}

inpEl.addEventListener("search", searchEventCb, true);
inpEl.addEventListener("change", changeEventCb, true);
inpEl.addEventListener("keydown", keydownEventCb, true);

答案 9 :(得分:1)

发现这篇文章,我意识到它有点老了,但我我可能有一个答案。这将处理十字,点退并点击ESC键的点击。我相信它可能写得更好 - 我还是比较新的javascript。这是我最终做的 - 我正在使用jQuery(v1.6.4):

var searchVal = ""; //create a global var to capture the value in the search box, for comparison later
$(document).ready(function() {
  $("input[type=search]").keyup(function(e) {
    if (e.which == 27) {  // catch ESC key and clear input
      $(this).val('');
    }
    if (($(this).val() === "" && searchVal != "") || e.which == 27) {
      // do something
      searchVal = "";
    }
    searchVal = $(this).val();
  });
  $("input[type=search]").click(function() {
    if ($(this).val() != filterVal) {
      // do something
      searchVal = "";
    }
  });
});

答案 10 :(得分:1)

试试这个,希望能帮到你

$("input[name=search-mini]").on("search", function() {
  //do something for search
});

答案 11 :(得分:1)

document.querySelectorAll('input[type=search]').forEach(function (input) {
   input.addEventListener('mouseup', function (e) {
                if (input.value.length > 0) {
                    setTimeout(function () {
                        if (input.value.length === 0) {
                            //do reset action here
                        }
                    }, 5);
                }
            });
}

ECMASCRIPT 2016

答案 12 :(得分:1)

这是实现这一目标的一种方法。您需要将增量属性添加到您的html中,否则它将无效。

window.onload = function() {
  var tf = document.getElementById('textField');
  var button = document.getElementById('b');
  button.disabled = true;
  var onKeyChange = function textChange() {
    button.disabled = (tf.value === "") ? true : false;
  }
  tf.addEventListener('keyup', onKeyChange);
  tf.addEventListener('search', onKeyChange);

}
<input id="textField" type="search" placeholder="search" incremental="incremental">
<button id="b">Go!</button>

答案 13 :(得分:0)

看起来没有很好的答案,所以我想我会添加另一个可能的解决方案。

// Get the width of the input search field
const inputWidth = $event.path[0].clientWidth;
// If the input has content and the click is within 17px of the end of the search you must have clicked the cross
if ($event.target.value.length && ($event.offsetX < inputWidth && $event.offsetX > inputWidth - 17)) {
    this.tableRows = [...this.temp_rows];
}

更新

const searchElement = document.querySelector('.searchField');
searchElement.addEventListener('click', event => {
  // Get the width of the input search field
  const inputWidth = $event.path[0].clientWidth;
  // If the input has content and the click is within 17px of the end of the search you must have clicked the cross
  if ($event.target.value.length && ($event.offsetX < inputWidth && $event.offsetX > inputWidth - 17)) {
    this.tableRows = [...this.temp_rows];
}
});

答案 14 :(得分:0)

我的解决方案基于onclick事件,我在事件触发的确切时间检查输入的值(确保它不为空),然后等待1毫秒并再次检查该值;如果为空,则表示单击了清除按钮,而不仅仅是输入字段。

下面是使用Vue函数的示例:

HTML

<input
  id="searchBar"
  class="form-input col-span-4"
  type="search"
  placeholder="Search..."
  @click="clearFilter($event)"
/>

JS

clearFilter: function ($event) {
  if (event.target.value !== "") {
    setTimeout(function () {
      if (document.getElementById("searchBar").value === "")
        console.log("Clear button is clicked!");
    }, 1);
  }
  console.log("Search bar is clicked but not the clear button.");
},

答案 15 :(得分:0)

基于js的事件循环,click清除按钮会在输入上触发search事件,因此下面的代码将按预期工作:

input.onclick = function(e){
  this._cleared = true
  setTimeout(()=>{
    this._cleared = false
  })
}
input.onsearch = function(e){
  if(this._cleared) {
    console.log('clear button clicked!')
  }
}

以上代码, onclick 事件预订了this._cleared = false个事件循环,但事件将 onsearch事件之后可以稳定地检查this._cleared状态,以确定用户是否只是点击了X按钮,然后触发了onsearch事件。

这可以在几乎所有条件粘贴文本增量属性, ENTER / ESC 键上工作按等。

答案 16 :(得分:0)

完整解决方案

单击搜索x时,将清除搜索。 要么 当用户点击进入时,将调用搜索API。 这个代码可以通过额外的esc keyup事件匹配器进一步扩展。但这应该做到这一切。

document.getElementById("userSearch").addEventListener("search", 
function(event){
  if(event.type === "search"){
    if(event.currentTarget.value !== ""){
      hitSearchAjax(event.currentTarget.value);
    }else {
      clearSearchData();  
    }
  }
});

干杯。

答案 17 :(得分:0)

我相信这是唯一一个在点击x时才会触发的答案。

然而,它有点hacky,ggutenberg的答案对大多数人都有用。

$('#search-field').on('click', function(){
  $('#search-field').on('search', function(){
    if(!this.value){
      console.log("clicked x");
      // Put code you want to run on clear here
    }
  });
  setTimeout(function() {
    $('#search-field').off('search');
  }, 1);
});

其中'#search-field'是您输入的jQuery选择器。使用'input[type=search]'选择所有搜索输入。通过点击该字段后立即检查搜索事件(Pauan的答案)来工作。

答案 18 :(得分:0)

搜索或onclick有效...但我发现的问题是旧浏览器 - 搜索失败。很多插件(jquery ui自动完成或fancytree过滤器)都有模糊和焦点处理程序。将此添加到自动完成输入框对我有用(使用this.value ==&#34;&#34;因为评估速度更快)。当你点击“x&#39;”时,模糊然后聚焦将光标保持在框中。

PropertyChange和输入适用于IE 10和IE 8以及其他浏览器:

$("#INPUTID").on("propertychange input", function(e) { 
    if (this.value == "") $(this).blur().focus(); 
});

对于FancyTree过滤器扩展,您可以使用重置按钮并强制它点击事件,如下所示:

var TheFancyTree = $("#FancyTreeID").fancytree("getTree");

$("input[name=FT_FilterINPUT]").on("propertychange input", function (e) {
    var n,
    leavesOnly = false,
    match = $(this).val();
    // check for the escape key or empty filter
    if (e && e.which === $.ui.keyCode.ESCAPE || $.trim(match) === "") {
        $("button#btnResetSearch").click();
        return;
    }

    n = SiteNavTree.filterNodes(function (node) {
        return MatchContainsAll(CleanDiacriticsString(node.title.toLowerCase()), match);
        }, leavesOnly);

    $("button#btnResetSearch").attr("disabled", false);
    $("span#SiteNavMatches").text("(" + n + " matches)");
}).focus();

// handle the reset and check for empty filter field... 
// set the value to trigger the change
$("button#btnResetSearch").click(function (e) {
    if ($("input[name=FT_FilterINPUT]").val() != "")
        $("input[name=FT_FilterINPUT]").val("");
    $("span#SiteNavMatches").text("");
    SiteNavTree.clearFilter();
}).attr("disabled", true);

应该能够适应大多数用途。

答案 19 :(得分:-1)

点击TextField十字按钮(X)onmousemove()被触发后,我们可以使用此事件来调用任何函数。

<input type="search" class="actInput" id="ruleContact" onkeyup="ruleAdvanceSearch()" placeholder="Search..." onmousemove="ruleAdvanceSearch()"/>