I have a form to update a user's profile and I want to alert users when they leave the password field blank.
Currently, when a user leaves the password field blank and submits the form, the alert box will come up. But after clicking the OK button on the alert, the page refreshes and somehow the user updates his password to blank...
Here's my code:
$userProfileForm.on("submit", handleUpdateUserProfile);
async function handleUpdateUserProfile(e) {
e.preventDefault();
const updatedUser = {
name: $("#edit-user-name").val(),
password: $("#edit-user-password").val(),
};
if (!updatedUser.password) {
alert("Password can't be empty!");
// not working. It still refreshes the page and set the password to empty
return false;
} else {
currentUser = await currentUser.updateProfile(updatedUser);
saveUserCredentialsInLocalStorage();
return true;
}
}
I also tried e.preventDefault()
but it's not working as well. Please tell me how I can prevent the page reload. Thanks!
Edit:
I changed return false
to return true
and it works...but I received a warning in the console saying [Violation] 'submit' handler took 1130ms jquery:5229
Could someone help me explain what's going on here?
Here's the new code:
$userProfileForm.on("submit", handleUpdateUserProfile);
async function handleUpdateUserProfile(e) {
e.preventDefault();
const updatedUser = {
name: $("#edit-user-name").val(),
password: $("#edit-user-password").val(),
};
if (!updatedUser.password) {
alert("Password can't be empty!");
// working now, the page doesn't refresh but receives a warning
return true;
} else {
currentUser = await currentUser.updateProfile(updatedUser);
saveUserCredentialsInLocalStorage();
// I have to use reload() to force the page upload
location.reload();
}
}
CodePudding user response:
You do not need to return anything from that code. The e.preventDefault() should handle not submitting -
plain js version
document.getElementById("myForm").addEventListener("submit", asyncsubmit)
async function asyncsubmit(e) {
e.preventDefault();
if (e.target.querySelector("[name=q]").value === "") alert("Don't leave empty")
else console.log(e.target.id)
}
<form id="myForm" action="https://www.google.com/search">
<input type="text" name="q">
<input type="submit" value="search">
</form>
jQuery version
$("#myForm").on("submit", asyncsubmit)
async function asyncsubmit(e) {
e.preventDefault();
if ($(e.target).find("[name=q]").val() ==="") alert("Don't leave empty")
else console.log(e.target.id)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<form id="myForm" action="https://www.google.com/search">
<input type="text" name="q">
<input type="submit" value="search">
</form>