JavaScript DOM Scripting By Example Adding and Removing Names Using the submit Event

Alter the event handler on line 4 to run when the form is submitted, not just when the submit button has been clicked. L

Alter the event handler on line 4 to run when the form is submitted, not just when the submit button has been clicked. Leave the callback function empty for now.

app.js
const form = document.querySelector('form');
const submitButton = form.querySelector('[type=Submit]');

submitButton.addEventListener('click', () => {

});
index.html
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>submit demo</title>
  <style>
  p {
    margin: 0;
    color: blue;
  }
  div,p {
    margin-left: 10px;
  }
  span {
    color: red;
  }
  </style>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

<p>Type 'correct' to validate.</p>
<form action="javascript:alert( 'success!' );">
  <div>
    <input type="text">
    <input type="submit">
  </div>
</form>
<span></span>

<script>
$( "form" ).submit(function( event ) {
  if ( $( "input:first" ).val() === "correct" ) {
    $( "span" ).text( "Validated..." ).show();
    return;
  }

  $( "span" ).text( "Not valid!" ).show().fadeOut( 1000 );
  event.preventDefault();
});
</script>

</body>
</html>

3 Answers

Michael Nicholas
Michael Nicholas
22,696 Points

Line 4 should read:

form.addEventListener('submit', () => {

As Danielle mentioned, you're adding the event listener to the form element instead of the submit button, and changing the event from 'click' to 'submit'.

Hi, you have to shift the focus on the form by selecting the form itself and then change the event type paying attention to lower case of submit type. Hope i was helpful ;)

Ella Ruokokoski
Ella Ruokokoski
20,694 Points

You shouldn't add any code to the html file. Just edit the code in the app.js file.