In HTML5, the search
input type appears with a little X on the right that will clear the textbox (at least in Chrome, maybe others). Is there a way to detect when this X is clicked in Javascript or jQuery other than, say, detecting when the box is clicked at all or doing some sort of location click-detecting (x-position/y-position)?
This question is related to
javascript
jquery
html
events
dom-events
Using Pauan's response, it's mostly possible. Ex.
<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>
It made sense to me that clicking the X should count as a change event. I already had the onChange event all setup to do what I needed it to do. So for me, the fix was to simply do this jQuery line:
$('#search').click(function(){ $(this).change(); });
based on event-loop of js, the click
on clear button will trigger search
event on input, so below code will work as expected:
input.onclick = function(e){
this._cleared = true
setTimeout(()=>{
this._cleared = false
})
}
input.onsearch = function(e){
if(this._cleared) {
console.log('clear button clicked!')
}
}
The above code, onclick event booked a this._cleared = false
event loop, but the event will always run after the onsearch
event, so you can stably check the this._cleared
status to determine whether user just clicked on X
button and then triggered a onsearch
event.
This can work on almost all conditions, pasted text, has incremental attribute, ENTER/ESC key press etc.
try this, hope help you
$("input[name=search-mini]").on("search", function() {
//do something for search
});
Bind search
-event the search box as given below-
$('input[type=search]').on('search', function () {
// search logic here
// this function will be executed on click of X (clear button)
});
I know this is an old question, but I was looking for the similar thing. Determine when the 'X' was clicked to clear the search box. None of the answers here helped me at all. One was close but also affected when the user hit the 'enter' button, it would fire the same result as clicking the 'X'.
I found this answer on another post and it works perfect for me and only fires when the user clears the search box.
$("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);
});
On click of TextField cross button(X) onmousemove() gets fired, we can use this event to call any function.
<input type="search" class="actInput" id="ruleContact" onkeyup="ruleAdvanceSearch()" placeholder="Search..." onmousemove="ruleAdvanceSearch()"/>
I want to add a "late" answer, because I struggled with change
, keyup
and search
today, and maybe what I found in the end may be useful for others too.
Basically, I have a search-as-type panel, and I just wanted to react properly to the press of the little X (under Chrome and Opera, FF does not implement it), and clear a content pane as a result.
I had this code:
$(some-input).keyup(function() {
// update panel
}
$(some-input).change(function() {
// update panel
}
$(some-input).on("search", function() {
// update panel
}
(They are separate because I wanted to check when and under which circumstances each was called).
It turns out that Chrome and Firefox react differently.
In particular, Firefox treats change
as "every change to the input", while Chrome treats it as "when focus is lost AND the content is changed".
So, on Chrome the "update panel" function was called once, on FF twice for every keystroke (one in keyup
, one in change
)
Additionally, clearing the field with the small X (which is not present under FF) fired the search
event under Chrome: no keyup
, no change
.
The conclusion? Use input
instead:
$(some-input).on("input", function() {
// update panel
}
It works with the same behaviour under all the browsers I tested, reacting at every change in the input content (copy-paste with the mouse, autocompletion and "X" included).
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
It doesn't seem like you can access this in browser. The search input is a Webkit HTML wrapper for the Cocoa NSSearchField. The cancel button seems to be contained within the browser client code with no external reference available from the wrapper.
Sources:
Looks like you'll have to figure it out through mouse position on click with something like:
$('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
}
});
The search or onclick works... but the issue I found was with the older browsers - the search fails. Lots of plugins (jquery ui autocomplete or fancytree filter) have blur and focus handlers. Adding this to an autocomplete input box worked for me(used this.value == "" because it was faster to evaluate). The blur then focus kept the cursor in the box when you hit the little 'x'.
The PropertyChange and input worked for both IE 10 and IE 8 as well as other browsers:
$("#INPUTID").on("propertychange input", function(e) {
if (this.value == "") $(this).blur().focus();
});
For FancyTree filter extension, you can use a reset button and force it's click event as follows:
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);
Should be able to adapt this for most uses.
Here's one way of achieving this. You need to add incremental attribute to your html or it won't work.
window.onload = function() {_x000D_
var tf = document.getElementById('textField');_x000D_
var button = document.getElementById('b');_x000D_
button.disabled = true;_x000D_
var onKeyChange = function textChange() {_x000D_
button.disabled = (tf.value === "") ? true : false;_x000D_
}_x000D_
tf.addEventListener('keyup', onKeyChange);_x000D_
tf.addEventListener('search', onKeyChange);_x000D_
_x000D_
}
_x000D_
<input id="textField" type="search" placeholder="search" incremental="incremental">_x000D_
<button id="b">Go!</button>
_x000D_
Full Solution is here
This will clear search when search x is clicked. or will call the search api hit when user hit enter. this code can be further extended with additional esc keyup event matcher. but this should do it all.
document.getElementById("userSearch").addEventListener("search",
function(event){
if(event.type === "search"){
if(event.currentTarget.value !== ""){
hitSearchAjax(event.currentTarget.value);
}else {
clearSearchData();
}
}
});
Cheers.
The original question is "Can I detect a click of the 'x'?".
This can be achieved by "sacrificing" Enter in the search
event.
There are many events firing at different times in the lifecycle of an input box
of type search: input
, change
, search
. Some of them overlap under certain circumstances. By default, "search" fires when you press Enter and when you press the 'x'; with the incremental
attribute, it also fires when you add/remove any character, with a 500ms delay to capture multiple changes and avoid overwhelming the listener.
The trouble is, search
generates an ambiguous event with input.value == ""
, because there are three ways it could have turned empty: (1) "the user pressed the 'x'", (2) "the user pressed Enter on an input with no text", or (3) "the user edited the input (Backspace, cut, etc) till the input became empty, and eventually incremental
triggered the search
event for the empty input".
The best way to disambiguate is to take Enter out of the equation, and have search
fire only when the 'x' is pressed. You achieve that by suppressing the Enter keypress altogether. I know it sounds silly, but you can get the Enter behavior back under better controlled circumstances via the keydown
event (where you'd do the suppressing too), the input
event or the change
event. The only thing that is unique to search
is the 'x' click.
This removes the ambiguity if you don't use incremental
. If you use incremental
, the thing is, you can achieve most of the incremental
behavior with the input
event (you'd just need to re-implement the 500ms debouncing logic). So, if you can drop incremental
(or optionally simulate it with input
), this question is answered by a combination of search
and keydown
with event.preventDefault()
. If you can't drop incremental
, you'll continue to have some of the ambiguity described above.
Here's a code snippet demonstrating this:
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);
_x000D_
<input type="search" id="inp" placeholder="Type something">
<textarea id="monitor" rows="10" cols="50">
</textarea>
_x000D_
In this simple snippet, you've turned search
into a dedicated event that fires only when you press 'x', and that answers the question originally posted. You track input.value
with the keydown
for Enter.
Personally, I prefer to put an ev.target.blur()
when pressing the Enter key (simulating a loss of focus for the input box), and monitor the change
event to track the input.value
(instead of monitoring input.value
via keydown
). In this way you can uniformly track input.value
on focus changes, which can be useful. It works for me because I need to process the event only if the input.value
has actually changed, but it might not work for everybody.
Here's the snippet with the blur()
behavior (now you'll get a message even if you manually focus away from the input box, but remember, expect to see a change message only if a change actually happened):
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);
_x000D_
<input type="search" id="inp" placeholder="Type something">
<textarea id="monitor" rows="10" cols="50">
</textarea>
_x000D_
Wow, there are some really complicated answers in here for a really simple problem.
Simply add a listener for 'input'
on your search input which will capture when the user types something in the input or clicks on the clear icon.
document.getElementById('searchInput').addEventListener('input', (e) => {
console.log(`Input value: "${e.currentTarget.value}"`);
})
_x000D_
<input id="searchInput" type="search" placeholder="Search" />
_x000D_
If you can't use ES6+ then here is the converted code for you:
document.getElementById('searchInput').addEventListener('input', function(e) {
// Yay! You make it in here when a user types or clicks the clear icon
})`
However, it is a bit hacky and ggutenberg's answer will work for most people.
$('#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);
});
Where '#search-field'
is the jQuery selector for your input. Use 'input[type=search]'
to select all search inputs. Works by checking for a search event (Pauan's answer) immediately after a click on the field.
Found this post and I realize it's a bit old, but I think I might have an answer. This handles the click on the cross, backspacing and hitting the ESC key. I am sure it could probably be written better - I'm still relatively new to javascript. Here is what I ended up doing - I am using 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 = "";
}
});
});
My solution is based on the onclick
event, where I check the value of the input (make sure that it's not empty) on the exact time the event fires and then wait for 1 millisecond and check the value again; if it's empty then it means that the clear button have been clicked not just the input field.
Here's an example using a Vue
function:
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.");
},
Source: Stackoverflow.com