Wednesday, March 21, 2012

Line limit for Text Area

In a HTML page, text area is used to accept multiple line texts at once. But some times, we may need to fixed the no. of line in a text area of web page. There is not attribute available for this purpose. This will have to implemented using javascript. The required function to check the no. of line as well as the no. of characters in a text area may be as:

<script type="text/javascript">

var alert_title='Input Restriction';

function limitTextarea(textarea,maxLines,maxChar){
var lines=textarea.value.replace(/\r/g,'').split('\n'),
lines_removed,
char_removed,
i;
if(maxLines&&lines.length>maxLines){
//alert('You can not enter\nmore than '+maxLines+' lines');
lines=lines.slice(0,maxLines);
lines_removed=1
}
if(maxChar){
i=lines.length;
while(i-->0)if(lines[i].length>maxChar){
lines[i]=lines[i].slice(0,maxChar);
char_removed=1
}
//if(char_removed)alert('You can not enter more\nthan '+maxChar+' characters per line')
}
if(char_removed||lines_removed)textarea.value=lines.join('\n')
}

function watchTextarea(){
document.getElementById('resticted').onkeyup()
}

function set_ie_alert(){
window.alert=function(msg_str){
vb_alert(msg_str)
}
}
</script>

and the above function can be called as

</script>
</head>
<body>
<textarea onkeyup="limitTextarea(this,6,40)" style="width:400px;height:200px" wrap="off" id="resticted" onfocus="focus_watch=setInterval('watchTextarea()',250)" onblur="clearInterval(focus_watch)">some text</textarea>
</body>
</html>

3 comments:

Unknown said...

thanks paul.

One suggestion : ur website color context is not good. It reflects to my eyes may be for others too. :) Change if possible make visitors for long time in ur site.

Thanks you.

Unknown said...

thanks paul.

One suggestion : ur website color context is not good. It reflects to my eyes may be for others too. :) Change if possible make visitors for long time in ur site.

Thanks you.

Unknown said...

This script is oh-so-close to what I'm looking for. How can it be modified to report progress... such as... 45 characters or 3 lines of text remaining.