问题
I am having two textboxes like this :
<p>
<input type="text" name="NPassword" placeholder="New Password"/></p>
<input type="text" name="RNPassword" placeholder="Retype New Password"/>
Now,what i want is that on every keypress of Retype New Password It should check if both are same or not.If yes then in green color display it on right side of RNPassword,Otherwise in red color display that both are not same and also disable the submit button of the page.How this can be done please help.
回答1:
Try this demo: ==> http://jsfiddle.net/uP8Q2/
Another demo = http://jsfiddle.net/ALk9Z/
disable button demo http://jsfiddle.net/K2Xdc/
2 things to start with:
- use
type=password
~> http://www.w3.org/TR/html-markup/input.password.html - use
.keyup()
API: http://api.jquery.com/keyup/
Also next time add your JS code with the post :)
rest should fit the need.
code
HTML
<p>
<input type="password" name="NPassword" placeholder="New Password" id="txtNewPassword" />
</p>
<input type="password" name="RNPassword" placeholder="Retype New Password" id="txtConfirmPassword" onChange="isPasswordMatch();" />
<div id="divCheckPassword"></div>
JS
function isPasswordMatch() {
var password = $("#txtNewPassword").val();
var confirmPassword = $("#txtConfirmPassword").val();
if (password != confirmPassword) $("#divCheckPassword").html("Passwords do not match!");
else $("#divCheckPassword").html("Passwords match.");
}
$(document).ready(function () {
$("#txtConfirmPassword").keyup(isPasswordMatch);
});
Disable button demo code
$('#hulk').prop('disabled' , true);
$('#txtConfirmPassword').on('keyup', function () {
var password = $("#txtNewPassword").val();
var confirmPassword = $("#txtConfirmPassword").val();
if (password != confirmPassword) {
$("#divCheckPassword").html("Passwords do not match!");
} else {
$("#divCheckPassword").html("Passwords match.");
$('#hulk').prop('disabled' , false);
}
});
回答2:
If you want to check that before submit you can do that in following way
With plain Jquery:
<p>
<input type="text" name="NPassword" id="first" placeholder="New Password"/></p>
<input type="text" name="RNPassword" id="second" placeholder="Retype New Password"/>
<span id="error" class="hidden">Not Matched"</span>
And then:
EDIT ONCHANGE
$('#second').keyup(function(e){
if($('#first').val() !== $('#second').val()){
$('#error').removeClass('hidden');
return false;
}else{
$('#error').addClass('hidden');
}
});
http://liveweave.com/yVXnIF
If you use KnockoutJs or AngularJs those have ability to bind verification in model itself.
来源:https://stackoverflow.com/questions/23258117/validating-password-and-retype-password