[英]What is the problem in code that alerts pop-up if I don't enter my ID or password?
I want to make a program that If I don't enter my ID or password, an alert pops up, and if my password is less than 6 characters, an alert pops up.我想做一个程序,如果我不输入我的 ID 或密码,就会弹出一个警报,如果我的密码少于 6 个字符,就会弹出一个警报。
When I ran this code, the 'Fill in the blank' and 'Enter the password with at least 6 characters' alerts always appeared even if I type letters in the ID and password boxes.当我运行此代码时,即使我在 ID 和密码框中输入字母,总是会出现“填空”和“输入至少 6 个字符的密码”警报。 If the condition is false, the alerts should not be displayed, but why does it appear?如果条件为假,则不应显示警报,但为什么会出现? I don't know what the problem is.我不知道问题是什么。
<form action="success.html">
<div class = "my-3">
<input type = "text" class = "form-control" id="id" placeholder="Fill in the blank">
</div>
<div class="my-3">
<input type = "password" class = "form-control" id="pw" placeholder="Enter the password with at least 6 characters">
</div>
<button type = "submit" class = "btn btn-primary">전송</button>
<button type = "button" class = "btn btn-danger" id="close">닫기</button>
</form>
<script>
var Text1 = $('#id').val();
var Password1 = $('#pw').val();
var passwordLength = $('#pw').val().length;
$('form').on('submit', function() {
if ( Text1 == '' || Password1 == '') {
alert('Fill in the blank')
}
if (passwordLength < 6){
alert('Enter the password with at least 6 characters')
}
}
)
</script>
always declare variables inside the function, and don't forget to add a return statement inside the IF statement to stop the function if certain validation is met.始终在函数内部声明变量,并且不要忘记在 IF 语句中添加 return 语句以在满足某些验证时停止函数。 Hope this is what you expect.希望这是你所期望的。
$('form').on('submit', function() { //Declare variables inside function var Text1 = $('#id').val(); var Password1 = $('#pw').val(); var passwordLength = $('#pw').val().length; if (Text1 == '' || Password1 == '') { alert('Fill in the blank'); return false;//use return statement } if (passwordLength < 6){ alert("Enter the password with at least 6 characters"); return false; } });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form action="success.html"> <div class = "my-3"> <input type = "text" class = "form-control" id="id" placeholder="Fill in the blank"> </div> <div class="my-3"> <input type = "password" class = "form-control" id="pw" placeholder="Enter the password with at least 6 characters"> </div> <button type = "submit" class = "btn btn-primary">전송</button> <button type = "button" class = "btn btn-danger" id="close">닫기</button> </form>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.