Search code examples
javascriptsubmitpreventdefault

Why doesn't e.preventDefault() stop my page from Refreshing?


I just can't figure out, why my site is loading when pushing the submit-btn. Even though I tried to prevent this with e.preventDefault() in my function. Maybe someone can open my eyes.. I'm sitting next to this (small) problem since 2 Days.

class Einkauf {
    constructor(produkt, anzahl){
        this.produkt = produkt;
        this.anzahl = anzahl;
    }
};

class UI {
    static showItems () {
        const items = [{
            Produkt: "Butter",
            Anzahl: 2
        },{
            Produkt: "Käse",
            Anzahl: 1
        }];

        items.forEach(item => UI.addItems(item));
    }

    static addItems (item) {
        const container = document.getElementById('grocery-list');
        const newItem = document.createElement('tr');
        newItem.innerHTML = 
        `<td>${item.Produkt}</td>
         <td>${item.Anzahl}</td>
         <td><a class="btn btn-danger btn-sm delete">x</a></td>`

         container.appendChild(newItem);
    }
};

document.addEventListener('DOMContentLoaded', UI.showItems());

//Neues Produkt einpflegen:
document.getElementById('btn').addEventListener('submit', (e) => {
    e.preventDefault();

    //Inputs definieren:
    const produkt = document.getElementById('produkt').value;
    const anzahl = document.getElementById('anzahl').value;

    const einkauf = new Einkauf(produkt, anzahl);
    
    UI.addItems(einkauf);
});
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Einkaufsliste</title>

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.2/css/all.min.css" integrity="sha512-1sCRPdkRXhBV2PBLUdRb4tMg1w2YPf37qatUFeS7zlBy7jJI8Lf4VHwWfZZfpXtYSLy85pkm9GaYVYMfw5BC1A==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootswatch@4.5.2/dist/yeti/bootstrap.min.css" integrity="sha384-mLBxp+1RMvmQmXOjBzRjqqr0dP9VHU2tb3FK6VB0fJN/AOu7/y+CAeYeWJZ4b3ii" crossorigin="anonymous">
</head>
<body>
    <div class="container mx-auto">
        <h1 class="text-center my-5 display-6">
            <span class="text-primary m-0">Einkaufs</span>
            liste
        </h1>
    

    <form id="form">
        <div class="form-group">
            <label for="produkt">Was fehlt?</label>
            <input type="text" id="produkt" class="form-control">
        </div>
        <div class="form-group">
            <label for="anzahl">Wie viel fehlt?</label>
            <input type="number" id="anzahl" class="form-control">
        </div>
        <input id="btn" type="submit" value="Hinzufügen" class="btn btn-primary btn-block"> 
    </form>

    <table class="table table-striped mt-5">
        <thead class="text-primary font-weight-bold">
            <td>Marke:</td>
            <td>Menge:</td>
            <td></td>
        </thead>
        <tbody id="grocery-list">

        </tbody>
    </table>

    </div>

    <script src="app.js"></script>
</body>
</html>

Maybe someone can figure the problem out and give me a short advice.

Best regards, Philipp.


Solution

  • You should instead be listening to the submit event on the form:

    document.getElementById('form').addEventListener('submit', function(e) {
      e.preventDefault()
    
      const produkt = document.getElementById('produkt').value;
      const anzahl = document.getElementById('anzahl').value;
    
      const einkauf = new Einkauf(produkt, anzahl);
    
      UI.addItems(einkauf);
    })
    
    class Einkauf {
      constructor(produkt, anzahl) {
        this.produkt = produkt;
        this.anzahl = anzahl;
      }
    };
    
    class UI {
      static showItems() {
        const items = [{
          Produkt: "Butter",
          Anzahl: 2
        }, {
          Produkt: "Käse",
          Anzahl: 1
        }];
    
        items.forEach(item => UI.addItems(item));
      }
    
      static addItems(item) {
        const container = document.getElementById('grocery-list');
        const newItem = document.createElement('tr');
        newItem.innerHTML =
          `<td>${item.Produkt}</td>
             <td>${item.Anzahl}</td>
             <td><a class="btn btn-danger btn-sm delete">x</a></td>`
    
        container.appendChild(newItem);
      }
    };
    
    document.addEventListener('DOMContentLoaded', UI.showItems());
    <!DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="UTF-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Einkaufsliste</title>
    
      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.2/css/all.min.css" integrity="sha512-1sCRPdkRXhBV2PBLUdRb4tMg1w2YPf37qatUFeS7zlBy7jJI8Lf4VHwWfZZfpXtYSLy85pkm9GaYVYMfw5BC1A==" crossorigin="anonymous" referrerpolicy="no-referrer"
      />
      <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootswatch@4.5.2/dist/yeti/bootstrap.min.css" integrity="sha384-mLBxp+1RMvmQmXOjBzRjqqr0dP9VHU2tb3FK6VB0fJN/AOu7/y+CAeYeWJZ4b3ii" crossorigin="anonymous">
    </head>
    
    <body>
      <div class="container mx-auto">
        <h1 class="text-center my-5 display-6">
          <span class="text-primary m-0">Einkaufs</span> liste
        </h1>
    
    
        <form id="form">
          <div class="form-group">
            <label for="produkt">Was fehlt?</label>
            <input type="text" id="produkt" class="form-control">
          </div>
          <div class="form-group">
            <label for="anzahl">Wie viel fehlt?</label>
            <input type="number" id="anzahl" class="form-control">
          </div>
          <input id="btn" type="submit" value="Hinzufügen" class="btn btn-primary btn-block">
        </form>
    
        <table class="table table-striped mt-5">
          <thead class="text-primary font-weight-bold">
            <td>Marke:</td>
            <td>Menge:</td>
            <td></td>
          </thead>
          <tbody id="grocery-list">
    
          </tbody>
        </table>
    
      </div>
    
      <script src="app.js"></script>
    </body>
    
    </html>
    
    Maybe someone can figure the problem out and give me a short advice. Best regards, Philipp.