I'm trying to add event/function on cross mark in search box with knockout.js, couldn't able to find any solution. Anyone have idea how to do it by using only knockout.js?
-
1Rohan, what's your definition of cross mark and search box? what are you doing with the cross mark that you need your app to react to? is there some code that you can share that would help illustrate the problem you are having?Nathan Fisher– Nathan Fisher2022-04-26 22:29:32 +00:00Commented Apr 26, 2022 at 22:29
-
@NathanFisher I don't have code, but I can explain, I have one list on that search is applied. If I type something in search box and clear it by backspace or "X" then I have to click search button or press enter to refresh my list. so wanted to add event on "X", if I type something in search box and click on "X" then it will automatically refresh the list(it will take to first page of list)Rohan Atyalkar– Rohan Atyalkar2022-04-27 06:10:08 +00:00Commented Apr 27, 2022 at 6:10
Add a comment
|
1 Answer
There is no specific event for this, but input fields do fire change and input events. So you can either listen to those, or just subscribe to the observable that's bound to the search input. If the new value is an empty string, the input field was cleared and you can do stuff.
function ViewModel() {
this.searchTerm = ko.observable();
this.searchTerm.subscribe((newVal) => {
if (newVal === '') {
console.log('Input was cleared');
}
});
}
ko.applyBindings(new ViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<input type="search" data-bind="textInput: searchTerm" />