<div class="searchbarhome">
<button id="glas" onclick="myFunction()"for="search"><i class="fa fa-search" aria-hidden="true"></i></button>
<input class="searchbox" type="text" id="myInput" onkeyup="myFunction()" placeholder="Zoek workshops.." title="Type in a name">
</div>
This is my html code
function myFunction(){
console.log('test');
// // Get the input field
var el = document.getElementById("myInput");
el.addEventListener("keydown", function(event) {
if (event.key === "Enter") {
var input = document.getElementById("myInput").value;
console.log(input)
localStorage.setItem("storageName",input);
console.log('Sending data');
document.location = 'search.php';
}
})
and this is my js code
as you can see i have a button and an input.
The function works on the input but i want to be able to press the button too. Now i dont know how i can make it so that the function checks for a keydown and a mouseup event
>Solution :
The current logic you have is wrong: in HTML you have attached myFunction as keyup handler to the input element, but then inside myFunction, you attach yet again an event handler to the input element. This practically means that every time the user releases a key in the input control, a new event handler is accumulated to that input element. This is going to accumulate…
Instead, remove the onclick and keypress attributes from your HTML and use addEventListener only.
Some other issues:
- Storing something in
localStorageis not going to get the string to the PHP server. - The
forattribute has no meaning for abuttonelement.
Then to your core question: just isolate the common part from what both events should do. As the check for the Enter-key is only for the event on the input element — and not for the button event — that part should not be in the common function.
Here is how it could look:
const inputElem = document.getElementById("myInput");
const buttonElem = document.getElementById("glas");
inputElem.addEventListener("keypress", (e) => {
if (e.key === "Enter") process();
});
buttonElem.addEventListener("click", process);
function process() { // Function with the common logic
// Common code:
console.log('test', inputElem.value);
// Other logic...
}
<div class="searchbarhome">
<button id="glas">Search</button>
<input class="searchbox" type="text" id="myInput" placeholder="Zoek workshops.." title="Type in a name">
</div>