Wysłanie formularza: submit i preventDefault
Formularze: odczyt pól i obliczenia - JavaScript na stronach WWW (HTML/CSS/JS)
Gdy pola są w `<form>`, lepiej obsłużyć zdarzenie `submit` formularza niż kliknięcie przycisku: działa też Enter w polu. Domyślnie wysłanie przeładowuje stronę, więc `e.preventDefault()` to zatrzymuje. Pola formularza są dostępne przez `form.elements` po nazwie (`name`). Po dodaniu wpisu formularz jest czyszczony metodą `reset()`.
<!DOCTYPE html>
<html lang="pl">
<head>
<meta charset="utf-8">
<title>Księga gości</title>
<style>
body { font-family: sans-serif; max-width: 36em; line-height: 1.4; }
input, select, button, textarea { font: inherit; padding: 0.2em 0.4em; }
table { border-collapse: collapse; }
th, td { border: 1px solid #94a3b8; padding: 0.2em 0.6em; }
</style>
</head>
<body>
<form id="guest">
<input name="author" placeholder="Imię" required>
<input name="text" placeholder="Wpis" required>
<button>Dodaj wpis</button>
</form>
<ul id="entries"></ul>
<script>
const form = document.getElementById('guest');
form.addEventListener('submit', e => {
e.preventDefault();
const author = form.elements.author.value.trim();
const text = form.elements.text.value.trim();
const li = document.createElement('li');
li.textContent = `${author}: ${text}`;
document.getElementById('entries').appendChild(li);
form.reset();
});
</script>
</body>
</html>Ładowanie interaktywnego edytora... Jeśli się nie pojawi, włącz JavaScript.
Wszystkie lekcje kursu JavaScript na stronach WWW·Zaloguj się, aby zapisać postęp na koncie.