I am setting up a form for a website and trying to set up an eventlistener, I am unsure as to why the form2 element cannot be read by the JS.
I have checked articles:
Cannot read value form <selected> element with JQuery/Javascript
Uncaught TypeError: Cannot read property 'value' of null
My form element has the correct id but still can not be read.
The HTML code is as follows:
<form onsubmit="AccountCreation(event)" id="form2">
<div class="accountcreation">
<h3>Account Creation</h3>
<p>To access the site please create an account.</p>
<hr>
<div class="form-group">
<label for="Username"><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="Username" required>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>
<label for="pswrepeat"><b>Repeat Password</b></label>
<input type="password" placeholder="Repeat Password" name="psw-repeat" required>
</div>
<div class="form-group">
<label for="Subjects">Choose subjects want to revise, holding control(CMD on mac) to pick multiple</label>
<select name = "Subjects" id="Subjects" multiple>
<option value="Maths">Maths</option>
<option value="Computer_Science">Computer Science</option>
<option value="Physics">Physics</option>
<!--Using a select for the form when creating the account allows me to easily add any future subjects once they have been added to the database-->
</div>
<input type="submit" value="Sign Up">
</form>
The JS is simply
document.getElementById('form2').addEventListener('submit', AccountCreation)
I am new to HTML and unsure if HTML handles form elements differently but could not find any definitive answer.
Console error:
Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')