I have a form on my website for people to sign up to a newsletter. The form is a single text box field (#input8), to which I have attached a dataset (#dataset2). After a user enters their email, I want them to be able to press the enter key on their keyboard to submit the form. On a successful submission I show a success message (#text37).
The code I have is as follows:
$w.onReady(function () {
$w("#input8").onKeyPress((event, $w) => {
if (event.key === "Enter") {
$w("#dataset2").save()
.then( () => {
$w("#text37").show("FadeIn");
});
}
});
});
What I want is that this code should work as follows:
1. User types in email into input
2. User clicks Enter key
(User's email is saved to the database)
However, the issue I am having is that this code only works if the user does the following:
1. User types email into input
2. User clicks off of input box
3. User clicks back into input box
4. User clicks Enter key
(User's email is saved to the database)
I am not sure why the onKeyPress seems to only work on the first key press. I expect the onKeyPress to be a binding event that is listening to all key presses in that input box.
Some additional information that may be helpful:
* The form and database are in the footer of my website
* The code is set in the site onReady function (not the page onReady function)
Has anyone had a similar issue and found a solution or work around?
Thanks
Hey Andreas,
You need to use debounce...
let debounceTimer; export function input1_keyPress(event, $w) { if (debounceTimer) { clearTimeout(debounceTimer); debounceTimer = undefined; } debounceTimer = setTimeout(() => { let val = $w('#input1').value; console.log(val); }, 500); }
or a simple timeout...
export function input1_keyPress(event, $w) { setTimeout(() => { let val = $w('#input1').value; console.log(val); }, 10); }
The debounce is more "robust" and is good to use in auto complete type functions where the user might type too fast causing code execution problems.
I hope this helps.
Yisrael