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" >First Name:</label> <br>
<input type="text" name="fName" id="fname" required> <br>
<label for="lName" ></label>Last Name:</label> <br>
<input type="text" name="lName" id="lName" required> <br>
<label for="emailA" ></label>Email Address:</label> <br>
<input type="email" name="Email" id="emailA" required><br>
<label for="password" ></label>Password</label> <br>
<input type="password" name="password" id="password" minlength="5" maxlength="12"> <br>
<input type="submit" value="Submit" id="formSubmit">
<input type="reset" value="Clear" >
</form>
CodePudding user response:
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'
CodePudding user response:
add an id to your form let say id="form1" and add this code:
var myform = document.getElementById("form1"); myfom.addEventListener('submit',function(e){e.preventDefault();});
<form role="form" id="form1">
<label for="fname" >First Name:</label> <br>
<input type="text" name="fName" id="fname" required> <br>
<label for="lName" ></label>Last Name:</label> <br>
<input type="text" name="lName" id="lName" required> <br>
<label for="emailA" ></label>Email Address:</label> <br>
<input type="email" name="Email" id="emailA" required><br>
<label for="password" ></label>Password</label> <br>
<input type="password" name="password" id="password" minlength="5"
maxlength="12"> <br>
<input type="submit" value="Submit" id="formSubmit">
<input type="reset" value="Clear" >
</form>
CodePudding user response:
formSubmit is not a variable. You must grab a reference to an element.
document.getElementById('formSubmit').addEventListener('click', function (event) {
event.preventDefault();
});
CodePudding user response:
Add a class "form" to your form element as a reference element. You should also not that i have used es6 syntax.
const form = document.querySelector('.form');
form.addEventListener('submit', (e) => e.preventDefault());
<form role="form">
<label for="fname" >First Name:</label> <br>
<input type="text" name="fName" id="fname" required> <br>
<label for="lName" ></label>Last Name:</label> <br>
<input type="text" name="lName" id="lName" required> <br>
<label for="emailA" ></label>Email Address:</label> <br>
<input type="email" name="Email" id="emailA" required><br>
<label for="password" ></label>Password</label> <br>
<input type="password" name="password" id="password" minlength="5" maxlength="12"> <br>
<input type="submit" value="Submit" id="formSubmit">
<input type="reset" value="Clear" >
</form>