سؤال

Hi is there a way to limit the words in textarea having the same function as maxlength do using jquery or coffeescript and with the use of keyup function as well because I need to display an accurate counter. I've been searching around but can't find a way to do this. I've tried this but it is on keypress and it's allowing the user to paste more than 250 words.

  $(document).on "keypress", '#company_desc', (e) ->
    s = $("#company_desc").val()
    s = s.replace(/(^\s*)|(\s*$)/g, "")
    s = s.replace(/[ ]{2,}/g, " ")
    s = s.replace(/\n /, "\n")
    count = s.split(" ").length
    $(".counter").html(250 - count + " words remaining")
    if count == 250
      key = (if e.charCode then e.charCode else (if e.keyCode then e.keyCode else 0))
      switch key
        when e.ctrlKey && key == keys[CTRL_A] then return true
        when e.ctrlKey && key == keys[CTRL_C] then return true
        when e.ctrlKey && key == keys[CTRL_X] then return true
        when e.ctrlKey && key == keys[CTRL_Z] then return true
        else return key == 46 || key == 8
هل كانت مفيدة؟

المحلول

your textarea add attr "maxlength"

try this.

$("your textarea id and class").attr("maxlength", 250);

نصائح أخرى

var maxWords = 150;
jQuery('textarea').keypress(function() {
var $this, wordcount;
$this = $(this);
wordcount = $this.val().split(/\b[\s,\.-:;]*/).length;
if (wordcount > maxWords) {
    jQuery(".word_count span").text("" + maxWords);
    alert("You've reached the maximum allowed words.");
    return false;
} else {
    return jQuery(".word_count span").text(wordcount);
}
});

fiddler: http://jsfiddle.net/qPvch/164/

So I came up with this.

var maxWords = 250;
jQuery('textarea').keyup(function() {
    var a, wordcount;
    a = $(this).val();
    a = a.replace(/(^\s*)|(\s*$)/g, "");
    a = a.replace(/[ ]{2,}/g, " ");
    a = a.replace(/\n /, "\n");
    wordcount = a.split(" ").length;
    if (wordcount == maxWords) {
        $(this).val(a.substr(0, a.length));
    }
    if (wordcount > maxWords) {
        $(this).val(a.substr(0, a.length - 1));
    }
    return jQuery(".word_count span").text(maxWords - wordcount + " words remaining");
});
$('textarea').bind("paste",function(e) {
        e.preventDefault();
    });

I used .substr(0, a.length -1) to cut off the words and to force the user to remain inside the maxWords, I also disabled pasting inside the textarea (this disables also right-click paste) but i don't think this is the best way, it is better if the user can still use paste and automatically cut the excess words after pasting or disable it when user already reached the max word like the maxlength do. Any suggestions? Here's my fiddle - JSFiddle

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top