jbcedge
jbcedge

Reputation: 19515

Forcing line break in the textarea after 38 characters using jquery

1Heres is my code but I am dont know how to add a line break and allow the user to continue typing. With the alert message is fine but I just want the user to continue typing and line break added by the script.

dom.query = jQuery.noConflict( true );
dom.query(document).ready(function() {
    // var myTA = dom.query('#remaining_chars');
    //alert(myTA[0].scrollHeight); 
    dom.query('#ta').keypress(function() {
        var text =dom.query(this).val();
        var arr = text.split("\n");
        for(var i = 0; i < arr.length; i++) {
            if(arr[i].length > 38) {
                alert("Not more than 38 characters per line! Continue in next line!");
                event.preventDefault(); // prevent characters from appearing
            }
        }

        console.log(text);
        dom.query('#ta').val(text);
    });
});

Link to the code :http://jsfiddle.net/e5w5z/8/1

Upvotes: 0

Views: 1764

Answers (1)

user1253034
user1253034

Reputation:

This code will automatically insert line breaks if the user continues to type and never backtracks. This only analyzes the last line in the textarea. Therefore, if they go back to a previous line and begin editing, they will be able to type more than the max characters allowed per line. It should be possible to have this analyze every line, but you'd have to write some more involved logic in order to insert line breaks at the correct positions and set the caret position properly after changing the textarea contents.

JSFiddle: http://jsfiddle.net/7V3kY/1/

var LINE_LENGTH_CHARS = 38;

$(function(){

    $(document).on('input propertychange','textarea',function(e){
        // Something was typed into the textarea
        var lines = $(this).val().split("\n");
        var last_line = lines[lines.length-1];
            if (last_line.length >= LINE_LENGTH_CHARS) {

                // Resetting the textarea val() in this way has the 
                // effect of adding a line break at the end of the 
                // textarea and putting the caret position at the 
                // end of the textarea
                $(this).val($(this).val()+"\n");

            }
    });
});

Upvotes: 1

Related Questions