2012-05-16 50 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); 
    } 
}); 
/*****************************/