EN
JavaScript - onsearch event example
0
points
In this article, we would like to show you onsearch
event example in JavaScript.
Quick solution:
var myElement = document.querySelector('#search-type-element');
myElement.addEventListener('search', function() {
console.log('onsearch event occurred.');
});
or:
<input type="search" onsearch="handleSearch()" value="Example text to search.">
or:
var myElement = document.querySelector('#search-type-element');
myElement.onsearch = function() {
console.log('onsearch event occurred.');
};
Note:
<input>
element type has to be defined assearch
.
Practical examples
There are three common ways how to use onsearch
event:
- with event listener,
- with element attribute,
- with element property.
1. Event listener based example
In this section, we want to show how to use onsearch
event on input
element via event listener mechanism.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<input type="search" id="my-input" value="Search this text.">
<script>
var myInput = document.querySelector('#my-input');
myInput.addEventListener('search', function() {
console.log('onsearch event occurred.');
});
</script>
</body>
</html>
2. Attribute based example
In this section, we want to show how to use onsearch
event on input
element via attribute.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<input type="search" onsearch="handleSearch()" value="Search this text.">
<script>
function handleSearch(){
console.log('onsearch event occurred.');
}
</script>
</body>
</html>
3. Property based example
In this section, we want to show how to use onsearch
event on input
element via property.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<input type="search" id="my-input" value="Search this text.">
<script>
var myInput = document.querySelector('#my-input');
myInput.onsearch = function() {
console.log('onsearch event occurred.');
};
</script>
</body>
</html>