Consider the following HTML code:
<form>
<div>
<input type ="text" id="myInput"/>
</div>
</form>
I would like that when the user write some text and press the ENTER key, the input value will change to the word "Hello".
To do so I add the following Java Script code:
<script>
var input = document.getElementById("myInput");
input.addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode === 13) {
input.value ="Hello";
}
});
</script>
Unfortunately, that didn't work as when I write a text and press the ENTER key, the text disappeared (instead of showing the world "Hello").
After digging a little into the problem I figured out that if I would remove the "form" tags from the HTML code, then it would work fine.
I have two questions:
1) Why this is happening?
2) How to solve this problem without removing the "form" tags?
Any help will be appreciated!!