David
David

Reputation: 4271

Textarea with max number of lines and max characters per line

I'm facing one issue where I need to develop textarea where number of lines must be 10 and maximum character per line - 15. Once the 16th character will be entered it must move to the next line.

Also we can't enter more than 10 lines. Here's what I am trying to do.

Onchange listener. I'm trying to restrict the user to enter 15 chars, but it's not happening. Below is my code. Any suggestions will be helpfull.

Ext.create('Ext.form.FormPanel', {
    title      : 'Sample TextArea',
    width      : 400,
    bodyPadding: 10,
    renderTo   : Ext.getBody(),
    items: [{
        xtype     : 'textareafield',
        grow      : true,
        name      : 'message',
        fieldLabel: 'Message',
        anchor    : '100%',
        listeners : {
            change : function(val,b){
                debugger;
                var text = val.getValue();
                var lines = text.split(/(\r\n|\n|\r)/gm); 
                 for (var i = 0; i < lines.length; i++) {
                    if (lines[i].length > 10) {
                        lines[i] = lines[i].substring(0, 10);
                    }
                }
                     text = lines.join('');
                //alert(val.value)
            }
        }
    }]
});

Here I have asked for number of charactes to each line and number of line is text area.

Upvotes: 1

Views: 351

Answers (1)

GriffoGoes
GriffoGoes

Reputation: 734

As a disclaimer, this type of solutions (on change listeners) are prone to complex problems: there are many ways to input content, such as drag-n-drop stuff into the textfield, copy/paste, etc. But here is a somehow working solution with some comments:

Ext.create('Ext.form.FormPanel', {
    title      : 'Sample TextArea',
    width      : 400,
    bodyPadding: 10,
    renderTo   : Ext.getBody(),
    items: [{
        xtype     : 'textareafield',
        grow      : true,
        name      : 'message',
        fieldLabel: 'Message',
        anchor    : '100%',
        numLines : 15,
        numCharsPerLine: 10,
        listeners : {
            change : function(val,b){
                var text = val.getValue();
                //console.log(text);
                var lines = text.split(/\r\n|\n|\r/); 
                 for (var i = 0; i < lines.length; i++) {
                    if (lines[i].length > this.numCharsPerLine) {
                        lines[i] = lines[i].substring(0, this.numCharsPerLine);
                    }
                }
                if(lines.length < this.numLines && lines[lines.length-1].length == this.numCharsPerLine) lines[lines.length-1] += "\n" ;
                lines = lines.slice(0,this.numLines); // limit line number
                 text = lines.join('\n');
                 //console.log(text);
                 this.setRawValue(text)
                //alert(val.value)
            }
        }
    }]
});

Upvotes: 2

Related Questions