简体   繁体   中英

How does event.preventDefault work on event handlers that cannot be stopped?

I'm trying to understand how event objects work in the context of the .preventDefault() method. Now I now for example, if I use event.preventDefault on the on submit event handler, it'll stop me from firing the submit event. So I tried to use onclick event handler on the submit button with the event.preventDefault(), it also didn't allow me to submit the form. Technically speaking it's not possible to not allow the user to click a button. So I want to make sure and know what exactly the event.preventDefault does exactly in relation to event handlers. The code for reference is below. This also bring me to the question, what is the natural behavior of buttons declared in the form but are not defined with type submit?

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Prevent default example</title>
    <style>
      div {
        margin-bottom: 10px;
      }
    </style>
  </head>
  <body>
    <form>
      <div>
        <label for="fname">First name: </label>
        <input id="fname" type="text">
      </div>
      <div>
        <label for="lname">Last name: </label>
        <input id="lname" type="text">
      </div>
      <div>
        <input id="submit" type="submit">
      </div>
    </form>
    <p></p>
    <script>
      var form = document.querySelector('form');
      var fname = document.getElementById('fname');
      var lname = document.getElementById('lname');
      var submit = document.getElementById('submit');
      var para = document.querySelector('p');
      form.onclick = function(e) {
        if(fname.value === '' || lname.value === '') {
          e.preventDefault();
          para.textContent = 'You need to fill in both names!'
        }
      }
    </script>
  </body>
</html>

The event.preventDefault function prevents the browser from executing the native behavior.

In the case of the submit button, it will not submit the data to the server and reload the page in the process, it will leave the data processing up to you.

So if you want to submit your form data with AJAX for instance, you can define in what way you handle the data.

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