2013-05-01 36 views
1

我使用textarea獲取評論和所有內容。我用jQuery>字計數器:刪除單詞時獲取遞增的計數器值

文本區域有字數限制或詞的maxlength。現在我將讓用戶知道可以輸入多少個字符。

雖然這是成功到現在,但我已經在刷新計數器值有問題。只要刪除字符,它就不會顯示計數器的刷新值。 另外當我做鍵控,然後計數器顯示從我開始刪除字符的舊值。

現在,如果文本區域是空的,我輸入的東西再反做工不錯。

我有一個小提琴這裏 -

Text area counter

步驟reproduce-

  1. 類型更長的句子。
  2. 現在從textarea中刪除這句話。
  3. 從textarea中刪除所有文本並重新開始輸入,它從全部單詞開始。

計數器沒有被示出刪除之後刷新值。

這是jQuery-

$(document).ready(function() { 
    var text_max = 300; 
    $('#textarea_feedback').html(text_max + ' characters remaining'); 

    $('#textarea').keypress(function() { 
     var text_length = $('#textarea').val().length; 
     var text_remaining = text_max - text_length; 

     $('#textarea_feedback').html(text_remaining + ' characters remaining'); 
    }); 
}); 

回答

2

的一些代碼,這是因爲你使用的是按鍵,使用keyup事件。

在Chrome和IE的按鍵事件將僅被壓可顯示的鍵時燒製。關鍵字如退格鍵和刪除鍵沒有顯示屬性,因此按鍵事件不會被觸發。

$(document).ready(function() { 
    var text_max = 300; 
    $('#textarea_feedback').html(text_max + ' characters remaining'); 

    $('#textarea').keyup(function() { 
     var text_length = $('#textarea').val().length; 
     var text_remaining = text_max - text_length; 

     $('#textarea_feedback').html(text_remaining + ' characters remaining'); 
    }); 
}); 

演示:Fiddle

+0

@Manoz對我來說看起來不錯 – 2013-05-01 04:24:34

+0

P Jhony:謝謝 – Manoj 2013-05-01 05:26:04

1

我以前有一個!

訣竅是使用keyup()代替keypress()

Fiddle

1

下面是我將如何捕獲所有更改。
另外,我會改變HTML有300或任何號碼的默認啓動,然後換你在另一個元素正在改變計數器的值,只有通過這個功能改變它的值。

$(document).ready(function() { 

    //Don't search for it over and over again 
    var $cachedSelector = $('#textarea_feedback'); 
    var $cachedTextArea = $('#textarea'); 

    //Common function you can call repeatedly that only updates the counter 
    function changeTextArea(){ 

     var text_length = $cahcedTextArea.val().length; 

     var text_remaining = 300 - text_length; 

     $cachedSelector.html(text_remaining); 
    } 

    //Handles Keyup or typing events 
    $cachedTextArea.keyup(function() { 
     changeTextArea() 
    }); 

    //Handles common chage events like if someone copy/pastes into your input 
    $cachedTextArea.change(function() { 
     changeTextArea() 
    }); 
});