TextArea with 10 lines and 35 characters per line - javascript

I have an HTML page with many elements. The page is scrollable, that means the page has a scrollbar in it. Down to the page I have a HTML textarea with a specified rows and columns attribute.
Now I want a simple JavaScript solution which will help me to validate the the following points each time user enters any character:
The number of lines in the textarea is not greater than 10
Each line has less than or equal to 35 characters
If user crosses 35 character limit for any particular line then the 36th character will be automatically start from next line only if the total line numbers does not exceed 10, else it will show an error popup message and stops there.
User should be able to modify any lines(it may be last line or any middle lines) and still should follow all the above 3 points.

I used the following to limit the amount of characters allowed in my textarea.
This not only counts the amount of characters it trims it if it gets to the end and it also writes out how many characters you have left.
I think all you need to do now is figure out how to add a new line (try something like text += "\r\n";) <- Not 100% sure on this peice.
function textCounter(txtfield, cntFld, maxlimit){
var field = document.getElementById(txtfield);
var countfield = document.getElementById(cntFld);
if (field.value.length > maxlimit) // if too long...trim it!
{
field.value = field.value.substring(0, maxlimit);
}else { // otherwise, update 'characters left' counter
countfield.innerHTML = maxlimit - field.value.length;
}
}

I have done a similar case :
MaxLenght of textarea = 1875 ;
MaxLenght of row = 75 ;
Disable Enter, because over 75's multiple, SW automatically wrap text ;
This is it, with onkeydown trigger:
function wrapTextArea(event,id,maxLineLenght){
// delete and canc
if((recuperaKeyCode(event)!=8) && (recuperaKeyCode(event)!=46)) {
var field = document.getElementById(id).value;
var nextIndex = 0;
for(var i=0; field.length>nextIndex; i++){
nextIndex=maxLineLenght*(i+1)+i;
if(field.length==nextIndex){
if(field.charAt(nextIndex)!= "\n"){
field=field.substring(0, nextIndex)+"\n"+field.substring(nextIndex, field.lenght);
}
}
}
document.getElementById(id).value = field;
}
}
This is how I disabled enter key, where key = 13 :
function disableKey(event,key){
if(recuperaKeyCode(event)==key){
event.preventDefault();
}
}

Related

How to detect new row in textarea while typing without setting Line height using JQuery?

Is there any way to detect in jQuery; whether new row got created in text area while end user is typing continuously in it? I could not set line height, max height of minheight of textarea.
Fiddle: http://jsfiddle.net/5wdzH/113/
Note: Here i am not asking about \n (Enter) but about new Row
enteredText = $( this ).val();
numberOfLineBreaks = (enteredText.match(/\n/g)||[]).length; //When we press enter then only the value comes but not for new row.
Textarea attributes:
$(e).css({'height': 'auto', 'overflow-y': 'hidden'}).height(e.scrollHeight);
I think best way to measure it will be counting number of columns of the text area and check if the number of characters entered exceeds that or not.This will not possibly hampered by wide letters or slim ones (except for one or two characters error margin).
var numberOfColumns = 0;
var numberOfLines = 1;
First:
$( "#watched_textarea" ).each(function(){
numberOfColumns = $(this).context.cols;
});
And then:
if (characterCount > numberOfColumns) {
numberOfLines = parseInt(characterCount / numberOfColumns) + 1;
}
You can have a look - updated your fiddle: http://jsfiddle.net/5wdzH/116/
There are two ways to do that
1) if you want to identify enter press then you can increase row counter
if(e.keyCode == 13) {
//increment row counter
}
2) if you are using fixed width of textarea then you can count number of words can fit in one row. no of character divide this factor to will give you number of rows
i think this will help you

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
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");
}
});
});

How to count and limit the text from 2 text fields in a form?

i tried to count and limit the user inputs from two text fields. that means max char is 20, then user can enter only 20 char in both text fields.I tried like this
$(document).ready( function() {
jQuery.fn.getLength = function(){
var count = 0;
var max=$("#max").val();
this.each(function(){
count += jQuery(this).val().length;
});
var rem=max-count;
return rem;
};
var $inputs= jQuery('#left,#right');
$inputs.bind('keyup',function(){
var remain=$inputs.getLength();
jQuery('#count').html($inputs.getLength());
$("#left").keyup(function(){
if($("#left").val().length > remain){
$("#left").val($("#left").val().substr(0, remain));
}
});
$("#right").keyup(function(){
if($("#right").val().length > remain){
$("#right").val($("#right").val().substr(0, remain));
}
});
});
});
but it only works for single text box, doesn't take values from 2 fields. any help please..
All you need is this code, it detects the keypress in either #left or #right, if the count of the two is more than 20, it removes the last character typed
$("#left,#right").keyup(function () {
var charCount = $('#left').val().length + $('#right').val().length;
if (charCount > 20) {
difference = -Math.abs(charCount - 20);
$(this).val($(this).val().slice(0, difference));
}
});
Demo http://jsfiddle.net/k8nMY/
My first solution worked on keydown and used return false to stop further entry, however this had the effect of disabling backspace and other keys.
This solution, which executes on keyup waits until after the key is pressed then counts characters. If the number is over 20 it will remove the last character typed. This way, the user can still press backspace and make changes as they wish, but not go over 20 chars.
I have also modified the script further, what it does is detect ANY change, e.g. a paste of a long string. It removes the 'difference' above 20 characters.
This should be a complete solution to the problem.
DEMO: http://jsfiddle.net/EEbuJ/2/
JQuery
$('#left, #right').keyup(function(e) {
if (maxLen() <= 20)
{
// Save the value in a custom data attribute
$(this).data('val', $(this).val());
} else {
// over-ride value with saved data
$(this).val($(this).data('val'));
}
});
function maxLen() {
var x = 0;
$('#left, #right').each(function() {
x += $(this).val().length;
});
return x;
};
This will save the typed in value for your inputs to a custom data attribute, if the total number of characters in the specified inputs is no more than 20.
When the maximum number of characters is reached then we stop saving the typed in value and revert the value back to our previous save (i.e. less than the maxiumum) effectively undo-ing the value.
Well it should be easy one: http://jsfiddle.net/4DETE/1/
var textLength =$inputs.eq(0).val().length+$inputs.eq(1).val().length;
if(textLength>=20)
return false
just count length of values, if you'll have more elements to limit, use jquery.each to iterate inputs
I doubt you can do $inputs.getLength() as $inputs is an array and thus will return the arraylength: 2
You will have to add up the overall sign length in both inputs:
$('#left,#right').keydown(function(){
var leftlength = $('#left').val().length;
var rightlength = $('#right').val().length;
if(leftlength + rightlength > 20)
{
return false;
}
});
or to make it shorter
if($('#left').val().length+$('#right').val().length >20){return false;}

keypress, keyup or keydown only work on the first ring in JQM

in my project have a jQuery Mobile textarea called "topic" on one page
I have this script I am using to count the characters entered in the textarea, but this script just gives me a result on the first keystroke. the other does not.
$(document).delegate("#topicDialog", "pageinit", function() {
$("#topic").keyup(function(e) {
var tam = $(this).length;
if (tam <= 61700){
$("#maxCarac").html(tam +" typed characters. The maximum allowed is 61700");
} else {
alert("You have reached the maximum text size.\nPlease break your text into more than one topic.");
$("#topic").val($("#topic").substring(61700));
}
});
});
example in action
What can be happening?
you need to use val().length
check the update fiddle here
$("#topic").keyup(function(e) {
var tam = parseInt($(this).val().length);
if (tam <= 61700){
$("#maxCarac").html(tam +" typed characters. The maximum allowed is 61700");
} else {
alert("You have reached the maximum text size.\nPlease break your text into more than one topic.");
$("#topic").val($("#topic").substring(61700));
}
});
http://jsfiddle.net/manishkumarshr/zdEzk/1/
this line needs to be changed
var tam = $(this).val().length;
See Demo
You are retrieving incorrectly the length of the user input. Use this:
var tam = $(this).val().length;
Here a working demo.

Limit text area value and cut the rest

I have a textarea which users can enter some tags.
I need to limit this tags to 20 tags.
Tags could be enterer this way
maytag1,mytag2,mytag3
What i wrote is this function
function limitTags()
{
var tags = $("input[type=text][name=tags]").val()
var tag = $.trim(tags);
var selected = new Array();
/**
* replace the last ','
*/
if(tag.substring(tag.length - 1) == ",")
{
*///tag = tag.replace(tag.length - 1, '');
}
var enteredTags = tag.split(",");
if( enteredTags.length > 20 )
{
//$("input[type=text][name=tags]").val(enteredTags.join(",", enteredTags));
alert("Only 20 Tags allowed");
}
}
The alert works just fine but, after the alert box is gone. i can continiue entering tags till the alert box appears.
What i need is cut the text after the messagebox which was entered also the last ","
I hope i could ask my question clear.
Thanks
You can use the slice method to cut the array down to 20 entries before setting the value:
$("input[type=text][name=tags]").val(enteredTags.slice(0,20).join(","));
See: https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array/Slice
Intercept "," pressing, and check how many entries the user inserted so far. If he's trying to insert too many entries just prevent further insertions.
$('input[type=text][name=tags]').keyup(function(e) {
if((e.keyCode == 188) && ($(this).val().split(",").length > 19)) {
alert('Only 20 Tags allowed');
}
});

Categories