I’m writing a script to take input from the user and greet him
But nothing happens on the page. There is an input form which takes an input and submits it. That’s it. It doesn’t print anything then.
What I’m doing wrong? How can I fix it?
I expect the code to print something like "Hello, Sam" where Sam is the user’s input.
<form>
<input type="text" id="firstName" name="firstName" />
<button type="submit">Submit</button>
</form>
<script>
let inp = document.getElementById("firstName").value;
console.log("Hello, " + inp);
</script>
3
Answers
Using a submit event listener, you can do this – I am using template literal to format the text:
You should create
.onsubmit
event for that form, so when the submit button clicks, do your task in the callback function. Don’t forget to doreturn false
if you want to disable redirect after submission.If you want the simple answer, here it is: