点击注册按钮无法触发SweetAlert提示?疑else语句存在问题
Hey there, let's get to the bottom of why your success SweetAlert isn't popping up when the user clicks the registration button! I've gone through your code and found two key issues that are causing this:
1. A Typo That's Breaking Your Code
First off, there's a silly syntax error in your password mismatch check that's stopping the code from reaching the else branch at all. Look at this line:
swal({ title: "",ant text: "Password Did Not Match", icon: "error", });
You wrote ant text instead of just text! This typo throws a JavaScript error when the passwords don't match, and if that happens, the rest of your code (including the success alert) never runs. Fix that line to:
swal({ title: "", text: "Password Did Not Match", icon: "error", });
2. Form Submission Is Cutting Off the Alert
Even after fixing the typo, you might still not see the success alert. That's because when you return true in the else branch, the form submits immediately—usually causing a page refresh before the alert can even render.
To fix this, you need to delay the form submission until after the user has seen the alert. Here's how to adjust the else block:
else{ swal({ title: "Thank You!", text: "Now you can access", icon: "success", }) .then(() => { // Only submit the form after the user closes the alert form.submit(); }); return false; // Prevent the default form submission right away }
Bonus: Clean Up Your Code a Bit
While we're at it, it's good practice to declare your variables properly with let or const to avoid polluting the global scope. For example:
let name = form.name.value; let mobile = form.mobile.value; // ... repeat this for all your form field variables
That should get your success alert showing up exactly when you want it!
内容的提问来源于stack exchange,提问作者Ahsan Habib

