Limiting lines and char count per line in a textarea with jQuery
I 开发者_开发百科have a Drupal webform with a textarea that I would like to limit the line and character per line when a option is selected, related to the textarea.
Example, user picks option A, the textarea should be limited to 2 lines, and 14 characters per line. Option B, 3 lines, with 18 characters. So on and so forth.
I cannot seem to interact with the webform through hook_form_alter to add attributes to the textarea for the javascript callback. I would assume that is my first issue. I was able to do it with jQuery however.
$(document).ready(function() {
$('#mytext').keyup(function() {
var v = $(this).val();
var vl = v.replace(/(\r\n|\n|\r)/gm, "").length;
if (vl == 0) {
count = 1;
}
if (parseInt(vl / count) == chars) {
$(this).val(v + '\n');
count++;
}
if (count > 3) {
var text = $('#mytext').val();
var lines = text.split('\n');
var test = implode('\n', lines);
alert(test);
}
});
});
Also, how can I count lines and characters per line, and prevent any typing if the limits are met?
I borrowed part of the above from here:
Characters per line and lines per textarea limit
This will limit textarea to 3 characters per line. Change chars
to increase number of characters per line.
var count = 1;
var chars = 3;
$('#mytext').keyup(function() {
var v = $(this).val();
var vl = v.replace(/(\r\n|\n|\r)/gm, "").length;
if (vl == 0) {
count = 1
}
if (parseInt(vl / count) == chars) {
$(this).val(v + '\n');
count++;
}
});
Check working example at http://jsfiddle.net/7jVrT/
This isn't exactly the right javascript, but it'll give you a good start I think. You have to really tinker with the logic to make sure you keep line 1 logic separate from line 2 logic, etc. Also, you can use event.which to figure out which key was pressed. And alternative to the keypress event, you can try using the keydown event which occurs before the character is typed in the textarea:
$(document).ready(function(){
$('#myTextarea').keypress(function(event){
var text = $('#myTextarea').val();
var lines = text.split('\n');
for (var lineIndex in lines) {
if (lines[lineIndex].length > 10) {
event.preventDefault();
return;
}
}
if (lines.length > 2) {
event.preventDefault();
return;
}
});
});
精彩评论