2012-05-16 52 views
0

我正在嘗試在jQuery Mobile的textarea中使用max-length,並且我遇到了一個奇怪的問題 - 問題是有或沒有在javascript中使用的返回false,textarea阻止我從15到60個字符的任何地方輸入文本太早..HTML5 Textarea最大長度儘早結束

maxLength屬性設置爲1150,我可以輸入1090和1115個字符。我不知道它是否是使用複製和粘貼的功能,因爲這是我測試它的唯一方法,但它似乎很奇怪。

下面是代碼:

$(document).delegate('#main','pageinit',function() { 
    $('#title,#description').keypress,function(e){ 

     var cur=$(this).val().length, 
     max=$(this).prop('maxLength'), rem=max-cur, 
     ch=$(this).parents('.ui-bar').find('.char-rem'), 
     red=$(this).parents('.ui-bar').find('.char-rem.red'),   
     green=$(this).parents('.ui-bar').find('.char-rem.green'); 

     ch.children('span').html(rem); 

     if(rem <= 10) 
     { 
      green.removeClass('green') 
      ch.addClass('red'); 
     } else {  
      red.removeClass('red') 
      ch.addClass('green') 
     } 
     if(rem == 0) 
     { 
      if(e.which!= 8) 
      { 
       return false; 
      } 
     } 

    }) 
}) 

每一次會發生什麼,是我得到了剩餘的字符一些低量 - 但大於0 - 我不能再鍵入。 同樣的事情發生,如果我刪除以下:

if(rem == 0) 
{ 
    if(e.which!= 8) 
    { 
     return false; 
    } 
} 

我跟的keydown嘗試這樣做,KEYUP以及和內部或外部pageinit,以及由各種其它的調整,我已經驗證字符串中的字符數帶textarea textLength屬性的textarea,每次結果都是一樣的。

現在,我使用Chromium來測試這個,我沒有在其他地方測試過它,但我想看看是否有什麼我只是想念。

任何線索?

+2

你輸入1190個字符還是複製粘貼?有時看不到空白字符進入圖片。 – Hindol

+0

看來你是對的。我發現這 - http://stackoverflow.com/questions/10030921/chrome-counts-characters-wrong-in-textarea-with-maxlength-attribute[/link],雖然我必須仔細檢查,這似乎是答案。 – user1167442

回答

0

我之前關於換行符的說明並不是答案。答案是,每次調用函數時,都會新讀取maxLength屬性。 出於某種原因,在閱讀maxLength屬性時,計數變得混亂了。

當我將maxLength值的變量切換到數字(1150)而不是使其讀取屬性時,它可以很好地工作。

與真正的答案編輯:

其實,真正的答案是,我有未關閉的HTML標籤,所以誰知道它在做什麼。當我固定標籤時,一切都很好

0

這是另一種解決方案。這個最大長度也將用於textareas。

/*****************************/ 
// SET MAX NUMBER OF CHARACTERS FOR ALL TEXTAREAS TROUGH ATTRIBUTE maxlength="*" 
jQuery('textarea[maxlength]').keyup(function(){ 
    //get the limit from maxlength attribute 
    var limit = parseInt($(this).attr('maxlength')); 
    //get the current text inside the textarea 
    var text = $(this).val(); 
    //count the number of characters in the text 
    var chars = text.length; 
    //Create counter, once 
    if (!jQuery(this).prev("span").length) { 
    jQuery(this).before('(Tecken <span class="charsleft"></span> av max ' + limit + ')'); 
    } 
    //Update counter 
    jQuery(this).prev('.charsleft').html(chars); 
    //check if there are more characters then allowed 
    if(chars > limit){ 
    //and if there are use substr to get the text before the limit 
    var new_text = text.substr(0, limit); 
    //and change the current text with the new text 
    jQuery(this).val(new_text); 
    } 
}); 
/*****************************/