我想驗證兩個輸入使用javascript
。我正在使用jQuery's .keypress()
事件來直接驗證輸入的值。這是我在laravel
框架代碼:爲什麼我無法使用jQuery的.keypress(),.keydown()和.keyup()事件正確比較兩個字符串?
HTML
<div class="form-group">
<label for="inputPassword"><h4>Password:</h4></label>
{{ Form::password('password',array('class'=>'span3 form-control', 'id'=>'password', 'placeholder'=>'Password')) }}
</div>
<div class="form-group">
<label for="verifyPassword"><h4>Verify Password:</h4></label>
{{ Form::password('password',array('class'=>'span3 form-control', 'id'=>'verify-password', 'placeholder'=>'Verify Password')) }}
</div>
<div class="form-group">
<div class="alert alert-danger hide" id="alert-verify-password-remove">
Password don't match!
<div class="glyphicon glyphicon-remove alert-icon-padding-remove"></div>
</div>
</div>
<div class="form-group">
<div class="alert alert-success hide" id="alert-verify-password-ok">
Password matched!
<div class="glyphicon glyphicon-ok alert-icon-padding-ok"></div>
</div>
</div>
JS
$(document).ready(function(){
$("#verify-password").keypress(function() {
// get password value from first password field
var pwd = $('#password').val();
// get the 2nd password value from the verify password field
var vPwd = $('#verify-password').val();
// verify the values if they are matched
// if matched then show match alert | hide unmatch alert
if (pwd == vPwd) {
$("#alert-verify-password-ok").removeClass('hide');
$("#alert-verify-password-remove").addClass('hide');
} // else, show unmatch alert | hide match alert
else {
$("#alert-verify-password-remove").removeClass('hide');
$("#alert-verify-password-ok").addClass('hide');
}
});
});
我的問題是,舉例來說,如果我打在#password
場test
然後在#verify-password
字段我必須鍵入tests
或第四個驗證前的任何字符va蓋住它是正確的/匹配的。這是顯示正在發生的事情的圖片。
正如你所看到的,我必須鍵入5(tests
)字符,而不是4(test
)之前確定的值相同。有人能告訴我這裏發生了什麼,至少給我適當的解決方案。謝謝。
我在你前面的問題評論回答了這個:http://stackoverflow.com/questions/24055587/why-jquerys-change-event-only-fires-on-右鍵單擊#comment37092503_24055631 - 您需要在場景中使用'keyup'而不是'keypress'。 –
@RoryMcCrossan抱歉,我沒有收到您對我以前的問題的回覆通知。我匆忙,這就是爲什麼我創造了新的問題。 –