2014-06-05 22 views
2

我想驗證兩個輸入使用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'); 
      } 
     }); 
}); 

我的問題是,舉例來說,如果我打在#passwordtest然後在#verify-password字段我必須鍵入tests或第四個驗證前的任何字符va蓋住它是正確的/匹配的。這是顯示正在發生的事情的圖片。

enter image description here

正如你所看到的,我必須鍵入5(tests)字符,而不是4(test)之前確定的值相同。有人能告訴我這裏發生了什麼,至少給我適當的解決方案。謝謝。

+3

我在你前面的問題評論回答了這個:http://stackoverflow.com/questions/24055587/why-jquerys-change-event-only-fires-on-右鍵單擊#comment37092503_24055631 - 您需要在場景中使用'keyup'而不是'keypress'。 –

+0

@RoryMcCrossan抱歉,我沒有收到您對我以前的問題的回覆通知。我匆忙,這就是爲什麼我創造了新的問題。 –

回答

4

因爲keypress發生前,字符串實際上是修改(因此你可以取消串變化)

使用keyup事件這些測試

... 
$("#verify-password").keyup(function() { 
... 

keyup改變串之後觸發,因此它們的值在測試中會與您看到的值相同

+0

我不喜歡.keyup()的東西哈哈。感謝你們! –

0

您需要使用keyup,因爲它的triggert在keypress之後。你可以看到這個例如here

$("#verify-password").keyup(function() { 
相關問題