EN
JavaScript - onsearch event example
0 points
In this article, we would like to show you onsearch
event example in JavaScript.
Quick solution:
xxxxxxxxxx
1
var myElement = document.querySelector('#search-type-element');
2
3
myElement.addEventListener('search', function() {
4
console.log('onsearch event occurred.');
5
});
or:
xxxxxxxxxx
1
<input type="search" onsearch="handleSearch()" value="Example text to search.">
or:
xxxxxxxxxx
1
var myElement = document.querySelector('#search-type-element');
2
3
myElement.onsearch = function() {
4
console.log('onsearch event occurred.');
5
};
Note:
<input>
element type has to be defined assearch
.
There are three common ways how to use onsearch
event:
- with event listener,
- with element attribute,
- with element property.
In this section, we want to show how to use onsearch
event on input
element via event listener mechanism.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<input type="search" id="my-input" value="Search this text.">
5
<script>
6
var myInput = document.querySelector('#my-input');
7
8
myInput.addEventListener('search', function() {
9
console.log('onsearch event occurred.');
10
});
11
</script>
12
</body>
13
</html>
In this section, we want to show how to use onsearch
event on input
element via attribute.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<input type="search" onsearch="handleSearch()" value="Search this text.">
5
<script>
6
function handleSearch(){
7
console.log('onsearch event occurred.');
8
}
9
</script>
10
</body>
11
</html>
In this section, we want to show how to use onsearch
event on input
element via property.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<input type="search" id="my-input" value="Search this text.">
5
<script>
6
var myInput = document.querySelector('#my-input');
7
8
myInput.onsearch = function() {
9
console.log('onsearch event occurred.');
10
};
11
</script>
12
</body>
13
</html>