i’ve just began my SWE bootcamp a few months ago and recently began learning about javascript
i was working on an assessment but kept getting this question wrong and was hoping someone would be able to explain this to me:
______________________________
There’s a form with a submit
event handler. Let’s say you want to validate the form fields before submitting, but the form is submitted before you can do anything with it. Write code to stop the form from submitting. Please enter your answer without a semicolon.
<form class="form">
<!-- ... -->
</form>
<script>
const form = document.querySelector(".form");
form.addEventListener("submit", function validateFields(event) {
// code here
});
</script>
______________________________
i entered preventDefault()
but that came out to be incorrect so i’m lost to what am i missing
2
Answers
The function
preventDefault()
is a property ofevent
, so the function call you need is:You’re on the right track by thinking of preventDefault(). But in order to use it properly, you need to call it on the
event
object within the submit event handler. This will prevent the form default submit action from occurring.So you should have written this code/line instead.