I am currently working to learn different Javascript features. I am working with preventDefault. I was attempting to practice on the website I am making, but it is still refreshing the page. What am I doing wrong?
This is my code:
formSubmit.addEventListener('click', function(event) {
event.preventDefault();
});
<form role="form">
<label for="fname" class="labelI">First Name:</label> <br>
<input type="text" name="fName" id="fname" required> <br>
<label for="lName" class="labelI"></label>Last Name:</label> <br>
<input type="text" name="lName" id="lName" required> <br>
<label for="emailA" class="labelI"></label>Email Address:</label> <br>
<input type="email" name="Email" id="emailA" required><br>
<label for="password" class="labelI"></label>Password</label> <br>
<input type="password" name="password" id="password" minlength="5" maxlength="12"> <br>
<input type="submit" value="Submit" class="but" id="formSubmit">
<input type="reset" value="Clear" class="but">
</form>
defer <script> tags right before the closing </body> tag.window properties for your ID selectors. Even if this might work for historical reasons, always create a variable reference to your DOM elements using querySelector() or querySelectorAll() Methods"click" Event when you actually want to listen to a "submit" event on the FORM itself. Such will also allow the browser to ignite the input-type attributes like required pattern etc.<body>
<form role="form" id="myForm">
<label for="fname" class="labelI">First Name:</label> <br>
<input type="text" name="fName" id="fname" required> <br>
<label for="lName" class="labelI"></label>Last Name:</label> <br>
<input type="text" name="lName" id="lName" required> <br>
<label for="emailA" class="labelI"></label>Email Address:</label> <br>
<input type="email" name="Email" id="emailA" required><br>
<label for="password" class="labelI"></label>Password</label> <br>
<input type="password" name="password" id="password" minlength="5" maxlength="12"> <br>
<input type="submit" value="Submit" class="but" id="formSubmit">
<input type="reset" value="Clear" class="but">
</form>
<!-- Place all your <script>s right BEFORE the closing BODY tag -->
<script>
const EL_myForm = document.querySelector("#myForm");
EL_myForm.addEventListener("submit", function (event) {
event.preventDefault(); // prevent default browser SUBMIT action
console.log("Form not submitted yet. Do your JS magic here!");
});
</script>
</body>
formSubmit is not a variable. You must grab a reference to an element.
document.getElementById('formSubmit').addEventListener('click', function (event) {
event.preventDefault();
});
You need to select button with id formSubmit.
var sel = document.getElementById("formSubmit");
sel.addEventListener('click',function(e){
e.preventDefault();
});
You cant add event listener directly to id 'formSubmit'