The return key in the input field refreshes the page

In two cases, press enter in the input box to trigger Submit

  1. In the form form, there is a button and an input box. Pressing enter in the box will trigger submit
  2. In the form form, there is no button, but there is only an input box, and press enter in the box will trigger Submit (other non-input form elements are optional).
<! -- Case 1: -->
  <form action="">
    <! -- Input box is ok, several do not matter -->
    <input type="text">
    <input type="text">
    <! -- It doesn't matter if there are other elements that are not input boxes -->
    <textarea name="" id="" cols="30" rows="10"></textarea>
    <button>sss</button>
  </form>

<! -- Case 2: -->
  <form action="">
    <! -- Only one input box -->
    <input type="text">
    <! -- It doesn't matter if there are other elements that are not input boxes -->
    <textarea name="" id="" cols="30" rows="10"></textarea>
  </form>
Copy the code

Solution 1: Remove the form tag

After all, the essence is to trigger the form submit event, so removing it will certainly solve the problem, but not necessarily suitable for removing.

Solution 2: Listen on Submit to block the default behavior

Listen on Submit to block the default behavior

<form onsubmit="event.preventDefault()">
<! -- js -->
<script>
  document.querySelector('form').addEventListener('submit'.function(e){
    e.preventDefault()
  })
</script>
Copy the code

Solution 3: Monitor carriage return events on input

Listen for carriage returns in each input:

<input type="text" name="aa" onkeypress="if(event.keyCode == 13){event.preventDefault()}">

<! -- return false -->
<! -- <input type="text" name="aa" onkeypress="if(event.keyCode == 13){return false}"> -->


<! -- js -->
<script>
  document.querySelector('form input').addEventListener('keypress'.function(e){
    if(event.keyCode == 13) {e.preventDefault()}
  })
</script>
Copy the code

Solution 4: Add a hidden input(without a button)

Add a hidden input without a button

  <form action="">
    <! -- Only one input box -->
    <input type="text">
    <! -- Add a hidden -->
    <input type="text" hidden>
    <! -- It doesn't matter if there are other elements that are not input boxes -->
    <textarea name="" id="" cols="30" rows="10"></textarea>
  </form>
Copy the code

The same problem applies to Element-UI

El-form /el-input/el-button is a native form/input/button, so it encounters the same problem.

The solution is similar:

  • Remove the el-Form form
  • <el-form @submit.native.prevent>
  • Add an input of type hidden without a button
  • Listen for input keypress, but it’s a bit more complicated

reference

  • HTML – Enter box Input Press Enter to automatically refresh the page solution
  • When an HTML form has only one text input, pressing Enter on the input automatically sends the form