textarea 行数限制_在textarea中限制单行中的行数和字母数量

Problem:

I am trying to limit number of lines AND letters in each line in a textbox.

What i got so far:

So far i managed to limit lines count using this:

var text = $(this).val();

var lines = text.split("\n");

if(e.keyCode == 13 && lines.length >= $(this).attr('rows')) {

return false;

}

This won't allow user to push return key (keyCode 13) if the limit of lines is reached.

The problem:

Now i am trying to limit number of letters in a single line too, because if i reach end of my textarea (with return key) i still can hold a letter/write tons of text, and it will jump to another line when it reaches end of line. That way this limitation can be "cheated" and i am looking for a solution for that.

My ideas, not solving the problem:

else{

for(var i = 0; i < lines.length && e.keyCode != 13; i++) {

if(lines[i].length >= $(this).attr('cols')) {

return false; // prevent characters from appearing

}

}

}

I tried this to limit number of letters. That works, but it got flaws. If i reach max letters in one line (ANY), i CANT TYPE IN ANY LINE anymore.

I have no idea how to check only line i am typing in RIGHT NOW.

解决方案$(document).ready(function(){

var textArea = $('#foo');

var maxRows = textArea.attr('rows');

var maxChars = textArea.attr('cols');

textArea.keypress(function(e){

var text = textArea.val();

var lines = text.split('\n');

if (e.keyCode == 13){

return lines.length < maxRows;

}

else{

var caret = textArea.get(0).selectionStart;

console.log(caret);

var line = 0;

var charCount = 0;

$.each(lines, function(i,e){

charCount += e.length;

if (caret <= charCount){

line = i;

return false;

}

//\n count for 1 char;

charCount += 1;

});

var theLine = lines[line];

return theLine.length < maxChars;

}

});

});​

Edit

As jbabey pointed out, ctrl+v or right-click -> paste can be an issue. right click can easily be prevented. for ctrl+v, you probable can detect it too...

Just disabling javascript will obviously break the thing, too.

Anyways, as any client-side validation, you have to double check on server-side.

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值