检查密码是否等于jQuery [英] Check if passwords are equal jQuery
本文介绍了检查密码是否等于jQuery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试验证输入的两个密码是否相同.但是我似乎无法正常工作.无论我在输入字段中输入什么值,结果始终为"true".可以看到我在做什么错吗?
I am trying to validate whether two entered passwords are the same or not. But I can't seem to get it working. No matter what values I enter in my input fields, the result is always "true". Can you see what I am doing wrong?
HTML:
<div class="form-group" id="password">
<input type="password" class="form-control" placeholder="Password" name="password">
</div>
<div class="form-group" id="repassword">
<input type="password" class="form-control" placeholder="Confirm Password" name="repassword">
</div>
jQuery:
//Check if password is set
$('input[name=password]').blur(function() {
if($(this).val().length == 0){
$('#password').addClass('has-error');
} else {
$('#password').addClass('has-success');
}
});
//Check if repassword is set
$('input[name=repassword]').blur(function() {
if($(this).val().length == 0){
$('#repassword').addClass('has-error');
} else {
$('#repassword').addClass('has-success');
}
});
//Check if password and repassword are equal
$('input[name=password]').blur(function() {
if ($(this).attr('value') !== $('input[name=repassword]').attr('value')) {
$('#password').addClass('has-error');
$('#repassword').addClass('has-error');
} else {
$('#password').addClass('has-success');
$('#repassword').addClass('has-success');
}
});
推荐答案
您应该使用.val()
获取文本框的值
You should be using .val()
to get the value of the textbox
您可以将整个过程简化为:
$('input').blur(function() {
var pass = $('input[name=password]').val();
var repass = $('input[name=repassword]').val();
if(($('input[name=password]').val().length == 0) || ($('input[name=repassword]').val().length == 0)){
$('#password').addClass('has-error');
}
else if (pass != repass) {
$('#password').addClass('has-error');
$('#repassword').addClass('has-error');
}
else {
$('#password').removeClass().addClass('has-success');
$('#repassword').removeClass().addClass('has-success');
}
});
DEMO
您可以改用$('input').blur(function()
,这样它将在所有输入上触发
You could use $('input').blur(function()
instead, that way it will trigger on all inputs
这篇关于检查密码是否等于jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文