简体   繁体   中英

Changing input value inside a form tags when ENTER key is pressed

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!!

  1. This is happening because "Enter" attempts to submit the form.

  2. Migrating your code to onSubmit event handler can fix the issue without removing the form tag.

I've attached the snippet. Let me know if this what you're expecting.

 <form onSubmit="changeToHello(event)"> <div> <input type ="text" id="myInput"/> </div> </form> <script> function changeToHello(event) { event.preventDefault(); var input = document.getElementById("myInput"); input.value ="Hello"; } </script> 

preventDefault() prevents the default behaviour of the event.

There is no default behaviour of a keyup event to prevent here, so it has no effect.

The keypress event runs too, and its default behaviour when you press enter is to submit the form.

The Form function in HTML looks to submit the data entered. Usually you would add an 'action' which just submits your form to a server (ie action="action.php"). Because there is no "action" you are essentially just refreshing the page. To get around this you would need to use AJAX and it's preventDefault() function to stop the form from submitting (refreshing the page).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM