The following uses the answer from https://stackoverflow.com/a/5047712/212869 to calculate the width of text, and I linked it to a textbox. Its really rough code :D but it does limit the textbox fairly well. The same principle could be used on a text area, but you would also have do it for both height and width.
http://jsfiddle.net/LMKtd/1/ - it outputs stuff to console so best to have it open if you have a look.
String.prototype.width = function(font) {
var f = font || '12px arial',
o = $('<div>' + this + '</div>')
.css({'position': 'absolute', 'float': 'left', 'white-space': 'nowrap', 'visibility': 'hidden', 'font': f})
.appendTo($('body')),
w = o.width();
o.remove();
return w;
}
$('#textinput').on('keyup', validatetext);
function validatetext(e) {
var w = parseInt(e.target.value.width());
if (w > 100) {
console.log("Width Gt 100px ["+w+"px] Char Count ["+e.target.value.length+"]");
do {
e.target.value = e.target.value.slice(0,-1);
} while (parseInt(e.target.value.width()) > 100)
} else {
console.log("Keep going! ["+w+"px] Char Count ["+e.target.value.length+"]");
}
}
Update
http://jsfiddle.net/LMKtd/8/
I've bodged together one for the text area too. It doesnt stop you going over the limits but it tells you when its too wide or tall. It's not very pretty :D
String.prototype.width = function(font) {
var f = font || '12px arial',
o = $('<div>' + this + '</div>')
.css({'position': 'absolute', 'float': 'left', 'white-space': 'nowrap', 'visibility': 'visible', 'font': f})
.appendTo($('body')),
w = o.width();
o.remove();
return w;
}
String.prototype.height = function(font) {
var f = font || '12px arial',
o = $('<div>' + this.replace(/[\r\n]/g,'<br />') + '</div>')
.css({'position': 'absolute', 'float': 'left', 'white-space': 'nowrap', 'visibility': 'hidden', 'font': f})
.appendTo($('body')),
w = o.height();
o.remove();
return w;
}
$('#textinput').on('keyup', validatetext);
$('#areainput').keyup(validatearea);
function validatearea(e) {
var w = parseInt($(this).val().width());
var h = parseInt($(this).val().height());
var errw = false;
var errh = false;
if (h>100) {
errh = true
}
var lines = $(this).val().split(/[\r\n]/);
var errw = false;
for (var i = 0; i<lines.length; i++) {
if (parseInt(lines[i].width()) > 100) {
errw = true;
}
}
if ((errh == true) || (errw == true)) {
if ((errh == true) && (errw == false)) {
$('#areaerror').html("Too Tall, Width OK");
}
if ((errh == false) && (errw == true)) {
$('#areaerror').html("Height OK, Too Wide");
}
if ((errh == true) && (errw == true)) {
$('#areaerror').html("Too Tall, Too Wide");
}
} else {
$('#areaerror').html("Were Good");
}
}
function validatetext(e) {
var w = parseInt(e.target.value.width());
if (w > 100) {
console.log("Width Gt 100px ["+w+"px] Char Count ["+e.target.value.length+"]");
do {
e.target.value = e.target.value.slice(0,-1);
} while (parseInt(e.target.value.width()) > 100)
} else {
console.log("Keep going! ["+w+"px] Char Count ["+e.target.value.length+"]");
}
}