I am following this tutorial https://www.learnwithjason.dev/blog/get-form-values-as-json/ but I have come across an issue in the first step of the tutorial (Step 1: Add a Listener to the submit Event for the Form). I am trying to make a function which gets the result of a button when it is clicked. It should return the data as a JSON. I have this code so far in my JavaScript file:
const handleFormSubmit = event => {
event.preventDefault();
const data = {};
const dataContainer = document.getElementsByClassName('results__display')[0];
dataContainer.textContent = JSON.stringify(data, null, " ");
}
const form = document.getElementsByClassName('contact-form')[0];
form.addEventListener('submit', handleFormSubmit);
Error: questionnaireGetData.js:4 Uncaught TypeError: Cannot read property 'addEventListener' of undefined at questionnaireGetData.js:4
QuestionnaireGetData is the name of the javascript file.
This is my HTML file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="js/questionnaire.js"></script>
<script src="js/questionnaireGetData.js"></script>
<title>Questionnaire</title>
</head>
<body>
<div id="outside">
<form class="contact-form">
<header>
<ul id="data"></ul>
<div id="radioButton"></div>
<div id="checkbox"></div>
</header>
<nav class="navbar">
<ul id="navbar-nav">
<li><button class ="backBtn"
onclick="window.location.href = './index.html';"
type="button"> Back
</button>
</li>
<li><button class="backBtn" id="submit"
type="button">Submit
</button></li>
</ul>
</nav>
</form>
</div>
</body>
</html>
I am currently getting an error in my console about this line:
form.addEventListener('submit', handleFormSubmit);
I don't have much experience with JavaScript and I can't figure out what i am doing wrong.