Skip to main content

Exercise 49

  • Create the following folder/file structure:
/ex_49
|-- index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Form elements event</title>
<style>
.error {
color: red;
background-color: pink;
border: 1px solid red;
padding: 5px;
}
</style>
</head>
<body>
<form
action="save_user.html"
method="post"
enctype="application/x-www-form-urlencoded"
name="login"
>
<input type="text" id="username" name="username" />
<input type="password" id="pass" name="pass" />
<input type="submit" name="submit" value="Send" />
</form>
<div id="errors"></div>
</body>
</html>

index.html

  • Create a basic HTML document
  • Create a script tag on the document head element
  • Select the form element using any of the JavaScript selectors
  • Add a form submit handler and prevent the default form behaviour
  • When the user submits the form validate that the username and password are not empty
  • If the fields are empty then add the error class to the error's id element
  • Also add the following messages:
Please input a username and password
  • If everything is ok then make sure that you don't show the error message
  • Then allow the form to be submitted