Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lära Challenge: Implement Event Listeners | Event Handling and User Interactions in JavaScript
Advanced JavaScript Mastery

book
Challenge: Implement Event Listeners

Task

You're building a form where users can submit their details. Your goal is to validate user input, provide real-time feedback as they type, and prevent form submission if the input is invalid.

  1. Real-Time Input Feedback:

    • Listen for changes as the user types;

    • Inside the event handler, check the length of the input value;

    • If it's less than 3 characters, set the content of the <p> with ID feedback to "Name is too short.";

    • If it's 3 characters or more, set feedback to "Name looks good!".

  2. Prevent Default Form Submission:

    • Listen for form submissions;

    • Stop the form from the default submitting behavior;

    • Check the input value;

    • If it's less than 3 characters, display "Please enter a longer name" in the <p> with ID form-message;

    • If it's 3 characters or more, display "Form submitted successfully!" in form-message.

html

index.html

css

index.css

js

index.js

copy
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="index.css" />
</head>
<body>
<h1>Sign Up Form</h1>
<form id="user-form">
<label for="name-input">Name:</label>
<input type="text" id="name-input" placeholder="Enter your name" />
<button id="submit-btn" type="submit">Submit</button>
<p id="feedback"></p>
<p id="form-message"></p>
</form>
<script src="index.js"></script>
</body>
</html>
  • Use the input event to listen for changes as the user types;

  • Use event.target.value.length < 3 to check the length of the input value;

  • Use the submit event to listen for form submissions;

  • Use event.preventDefault() to stop the form from the default submitting behavior;

  • Use nameInput.value.length < 3 to check the input value.

html

index.html

css

index.css

js

index.js

copy
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="index.css" />
</head>
<body>
<h1>Sign Up Form</h1>
<form id="user-form">
<label for="name-input">Name:</label>
<input type="text" id="name-input" placeholder="Enter your name" />
<button id="submit-btn" type="submit">Submit</button>
<p id="feedback"></p>
<p id="form-message"></p>
</form>
<script src="index.js"></script>
</body>
</html>

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 3. Kapitel 3

Fråga AI

expand
ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

We use cookies to make your experience better!
some-alt