jeudi 9 novembre 2017

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.

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




Aucun commentaire:

Enregistrer un commentaire