I want to get the value inside the input box and display it on the console
<form action="#">
name : <input type="text" id="name">
</form>
let name = document.getElementById('name').value;
console.log(name);
But it is returning empty in console log. How can I get the value from input box?
Thanks
You can use keyup event on input for when you type in input it will display value in console like below example:
const nameInput = document.getElementById('name');
nameInput.addEventListener("keyup", (e)=> {
console.log(nameInput.value)
});
<form action="#">
name : <input type="text" id="name">
</form>
You are getting a blank value of the input field because you have not added any value attribute in the input field. So you have to add a value attribute in the input field.
let name = document.getElementById('name').value;
console.log(name);
<form action="#">
name : <input type="text" id="name" value="my custom value">
</form>
Add a button to initiate form submit
<form action="#" id="form1">
name : <input type="text" id="name">
<input type="submit" value="Submit">
</form>
Now add event listener for Submit event
document.getElementById("form1").addEventListener("submit", function(e) {
// Prevent default behavior to avoid page refresh
e.preventDefault();
let name = document.getElementById('name').value;
console.log(name);
})