2015-08-30 42 views
0

我想爲使用JQuery的input[type='text']作爲用戶輸入設置maxlength屬性。所以當input[type='text']達到最大值時,它不會繼續。設置maxlength輸入JQuery失敗

這裏是我的代碼

$(document).ready(function(){ 
    $('input#nama').keyup(function(){ 
     if(check($('input#username'),5)){ 
      e.preventDefault(); 
      e.stopPropagation(); 
     } else { 
      $('input#username').val($(this).val()); 
     } 
    }); 

    function check(text,max){ 
     if(text.length > 5){ 
      return true; 
     } else { 
      return false; 
     } 
    } 
}); 

的問題是input[type='text']繼續充滿雖然它已經達到了最大值

回答

0

由於check函數的第一個參數是string和你逝去的DOM對象。雖然調用函數check傳遞值input而不是傳遞完整的對象。考慮以下幾點:

check($('input#username').val(),5) 
         ^^^^^^ ===> //Calling function pass value 

完整代碼:

$(document).ready(function(){ 
    $('input#nama').keyup(function(){ 
     if(check($('input#username').val(),5)){ //updated here 
      e.preventDefault(); 
      e.stopPropagation(); 
     } else { 
      $('input#username').val($(this).val()); 
     } 
    }); 

    function check(text,max){ 
     if(text.length > 5){ 
      return true; 
     } else { 
      return false; 
     } 
    } 
}); 
+0

哦,是的。這是愚蠢的錯誤。我檢查了字符串而不是'input [type ='text']的值'非常感謝你 –

+0

我希望你的問題解決了。請接下來不要使用SO發佈調試幫助,直到其必要。你可以接受答案。發佈問題之前學習正確的調試腳本。享受腳本。 – Manwal

+0

對不起,但我可以提出另一個問題。當'input [type ='text']'還沒有達到最大值時,它是可編輯的,但是當它已經達到它不再可編輯時,儘管我已經清空了觸發輸入#nama'。你能告訴我如何解決它嗎? –