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

shobha gunupuru
shobha gunupuru
1,137 Points

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

how to solve this

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

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

  form.preventDefault();

});
index.html
<!DOCTYPE html>
<html>
<head>
  <title>Submit Event</title>
</head>
<body>
<form>
  <label>Name:</label>
  <input type="text" name="name">
  <input type="Submit" name="submit" value="Submit">
</form>
  <script src="app.js"></script>
</body>
</html>

5 Answers

Cosimo Scarpa
Cosimo Scarpa
14,025 Points

Need to be

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

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

});

You're adding the EventListener to the form element instead of the submit button, also you need submit and not click.

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

form.addEventListener('submit', (e) => { e.preventDefault();

});

Steven Parker
Steven Parker
172,140 Points

You forgot to format it, but yes, that's what it would look like after you apply the hints I gave.

When posting code, always format using the instructions in the Markdown Cheatsheet pop-up, found below the "Add an Answer" area :arrow_heading_down:

Steven Parker
Steven Parker
172,140 Points

You need to make two changes to how this event listener is attached.

First, you would want to attach the listener to the form itself instead of the button. Then, you would want to change the event type (the first argument to addEventListener) from "click" to "submit".

Also, it looks like you already have code added for task 2. Did you pass task 1 already somehow?

But your task 2 code isn't quite right. You have the right idea in calling preventDefault, but it should be applied to the event object (e) instead of the form.

I could be totally wrong here but I'm thinking it's something like this:

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

form.preventDefault(); // this line is preventing submit

});

I just checked the challenge and that worked fine. I did leave out the form.preventDefault(); since that wasn't needed.

vikram 11023
vikram 11023
12,042 Points

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.

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

form.addEventListener('submit', (e) => {
const text = input.value; input.value = ''; });