Word wrap in multiline textbox after 35 characters

Posted by Kanavi on Stack Overflow See other posts from Stack Overflow or by Kanavi
Published on 2012-06-14T10:29:41Z Indexed on 2012/06/22 15:16 UTC
Read the original article Hit count: 249

Filed under:
|
|
<asp:TextBox CssClass="txt" ID="TextBox1" runat="server"
             onkeyup="CountChars(this);" Rows="20" Columns="35" 
             TextMode="MultiLine" Wrap="true">
</asp:TextBox>

I need to implement word-wrapping in a multi-line textbox. I cannot allow users to write more then 35 chars a line. I am using the following code, which breaks at precisely the specified character on every line, cutting words in half. Can we fix this so that if there's not enough space left for a word on the current line, we move the whole word to the next line?

function CountChars(ID) {
    var IntermediateText = '';
    var FinalText = '';
    var SubText = '';
    var text = document.getElementById(ID.id).value;
    var lines = text.split("\n");
    for (var i = 0; i < lines.length; i++) {
        IntermediateText = lines[i];
        if (IntermediateText.length <= 50) {
            if (lines.length - 1 == i)
                FinalText += IntermediateText;
            else
                FinalText += IntermediateText + "\n";
        }
        else {
            while (IntermediateText.length > 50) {
                SubText = IntermediateText.substring(0, 50);
                FinalText += SubText + "\n";
                IntermediateText = IntermediateText.replace(SubText, '');
            }
            if (IntermediateText != '') {
                if (lines.length - 1 == i)
                    FinalText += IntermediateText;
                else
                    FinalText += IntermediateText + "\n";
            }
        }
    }
    document.getElementById(ID.id).value = FinalText;
    $('#' + ID.id).scrollTop($('#' + ID.id)[0].scrollHeight);
}

Edit - 1

I have to show total max 35 characters in line without specific word break and need to keep margin of two characters from the right. Again, the restriction should be for 35 characters but need space for total 37 (Just for the Visibility issue.)

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery