I need to run some code after the user picks the data and year from the input element my HTML page
Here is my JavaScript code
var key_form = document.getElementById("key-form");
key_form.addEventListener("input", function () {
setTimeout(function(){let key = key_form.value; alert(key);}, 4000)
})
Here is the HTML
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Starter Template</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="src/script.js" defer></script>
<link rel="stylesheet" href="src/styles.css"/>
</head>
<body>
<label for="key-form">Pick date for key: </label>
<input type="date" id="key-form"/>
<label for="word">Word to encrypt: </label>
<input type="text" id="word"/>
</body>
</html>
Is there a better way to do this?
EDIT:
I don’t want it to have a hard 4 seconds limit then run the code which it does. I want it to only run the function when the user is done with giving input.
P.S sorry if question was not clear
So, the question is: How do you know "when the user is done with giving input"?
Maybe your form has a submit button that the user must click?
const key_form = document.getElementById("key-form");
const submit_button = document.getElementById("submit-button");
submit_button.addEventListener("click", function () {
let key = key_form.value;
alert(key);
})
<label for="key-form">Pick date for key: </label>
<input type="date" id="key-form"/>
<label for="word">Word to encrypt: </label>
<input type="text" id="word"/>
<button id="submit-button">Encrypt word!</button>
Or maybe when the focus is no longer on the date field?
(the blur event fires when a you click outside of the field or press tab when the field has focus)
const key_form = document.getElementById("key-form");
key_form.addEventListener("blur", function () {
let key = key_form.value;
alert(key);
})
<label for="key-form">Pick date for key: </label>
<input type="date" id="key-form"/>
<label for="word">Word to encrypt: </label>
<input type="text" id="word"/>
There are other ways too. Lots of events get fired as form fields get filled out, and they can all trigger any logic you want. So think about how you want the user to interact with this form, then find the right events to support that.