简体   繁体   中英

wordwrap for textarea using javascript or jquery

I need functionality that textarea should contain max 5 lines and each line should contain max 15 chars, when user writes 2 words eg 123456 123456789 and if that line char limit exceeds 15, then it should bring the 2nd word in next line along with \\n char in first line (means 123456 will be in first line along with \\n and 123456789 will be in 2nd) , I need to maintain \\n (replacing <br >) in my db for some reasons.

i wrote this code, which gives fuzzy result in some conditions

<textarea onkeypress="charCountTextarea('txt1',event,'75','14')" id="txt1"></textarea> 

var countLines=0;

var newLines;

function charCountTextarea(textAreaId,e,limit,lineLen)
{   

       newLines = $("#"+textAreaId).val().split("\n").length;
       var t = $("#"+textAreaId)[0];
       var lineIndex = t.value.substr(0, t.selectionStart).split("\n").length-1;

    //console.log("new lines"+lineIndex);
        if(newLines >= 5 && $("#"+textAreaId).val().split("\n")[lineIndex].length>lineLen)
        {

            if( e.keyCode!=8 && e.keyCode!=46 && e.keyCode!=33 && e.keyCode!=34 && e.keyCode!=35 && e.keyCode!=36 && e.keyCode!=37 && e.keyCode!=38 && e.keyCode!=39 && e.keyCode!=40)
            {
                e.preventDefault();
                return false;
            }
        }


        else
        if($("#"+textAreaId).val().split("\n")[lineIndex].length>=lineLen)  // which will count the total line char condition
        {
            console.log($("#"+textAreaId).val().split("\n")[lineIndex][lineLen-1]);


            if($("#"+textAreaId).val().split("\n")[lineIndex][lineLen-1].indexOf(" ")==-1 && e.keyCode!=8 && e.keyCode!=46 && e.keyCode!=33 && e.keyCode!=34 && e.keyCode!=35 && e.keyCode!=36 && lineIndex != 4 && newLines<5)
            {
                // to bring the word in next line
                var str = $("#"+textAreaId).val(), replacement = '\n';
                str = str.replace(/ ([^ ]*)$/,replacement+'$1');
                $("#"+textAreaId).val(str);

            }
            else
            if(e.keyCode!=8 && e.keyCode!=46 && e.keyCode!=33 && e.keyCode!=34 && e.keyCode!=35 && e.keyCode!=36 && lineIndex!=4 && newLines<5)
            {
                // to insert next line              
                insertTextAtCaret(document.getElementById(textAreaId), "\n");
            }


        }

        if(e.keyCode == 13 && newLines >= 5) 
        {
            //linesUsed.css('color', 'red');
            e.preventDefault();
            return false;
        }

}
function charCountTextarea(textAreaId,e,limit,lineLen)
{   

    var code = e.charCode || e.keyCode;

    newLines = $("#"+textAreaId).val().split("\n").length;
    var t = $("#"+textAreaId)[0];
    var lineIndex = t.value.substr(0, t.selectionStart).split("\n").length-1;
    console.log('val t :'+$("#"+textAreaId).val()+' line index : '+lineIndex+' new lines '+newLines);

    if(lineIndex == 10 && $("#"+textAreaId).val().split("\n")[lineIndex].length>(lineLen+1) && code!=8 && code!=46 && code!=33 && code!=34 && code!=35 && code!=36 && code!=37 && code!=38 && code!=39 && code!=40)
    {
        $("#"+textAreaId).val(($("#"+textAreaId).val()).substring(0, $("#"+textAreaId).val().length - 1));
        alert('You are reached to limit');
        return false;
    }

    if(lineIndex<5)
    {
        $("#"+textAreaId).val($("#"+textAreaId).val().wordWrap(lineLen, "\n", 0));
    }
    var countLine1 = $("#"+textAreaId).val().split("\n")[0].length;

    if($("#"+textAreaId).val().split("\n")[lineIndex].length>lineLen)  // which will count the total line char condition
    {
        console.log("In condition : ");
        if(code!=8 && code!=46 && code!=33 && code!=34 && code!=35 && code!=36 && code!=37 && code!=38 && code!=39 && code!=40)
        {
            // to insert next line              
            insertTextAtCaret(document.getElementById(textAreaId), "\n");
        }
    }
}

You can not know if the input will be fed using keyboard. I could just use the mouse to paste a text there.

I would rely on a function that would constantly check the input and take the action you want, which I would execute using the setInterval() function once the textarea is focused, which then gets cleared using clearInterval() once the textarea loses focus.

And this function would use a RegExp to process the input and split it into necessary lines.

EDIT: Here's what I mean.

$('body').on('focus','#txt1',function(e) {
    $(this).data('int',setInterval(checkInput,1));
}).on('blur','#txt1',function(e) {
    clearInterval($(this).data('int'));
    $(this).removeData('int');
});

function checkInput() {
    var val = $('#txt1').val();
    // process val here
    $('#txt1').val(val);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM