<script type="text/javascript">
function checking(textarea, maxLines, maxChar) {
var lines = textarea.value.replace(/\r/g, '').split('\n'), lines_removed, char_removed, i;
if (maxLines && lines.length > maxLines) {
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 || lines_removed) {
textarea.value = lines.join('\n')
}
}
}
</script>
这是我以前几篇文章中使用的内容。但是这段代码允许我输入&#39; n&#39; &#39; m&#39;中的字符数行数。有人可以帮我写一个只需30个字符和2行的代码吗? {假设第一行包含10个字符,则下一行应包含20个字符,但字符总数应为30,行数为2。}
答案 0 :(得分:1)
希望以下代码可以节省您的时间。
将以下JavaScript函数插入页眉:
<script language="javascript" type="text/javascript">
function limitText(limitField, limitCount, limitNum) {
if (limitField.value.length > limitNum) {
limitField.value = limitField.value.substring(0, limitNum);
} else {
limitCount.value = limitNum - limitField.value.length;
}
}
</script>
将以下代码插入到页面正文中:
<form name="myform">
<input name="limitedtextfield" type="text" onKeyDown="limitText(this.form.limitedtextfield,this.form.countdown,15);"
onKeyUp="limitText(this.form.limitedtextfield,this.form.countdown,15);" maxlength="15"><br>
<font size="1">(Maximum characters: 15)<br>
You have <input readonly type="text" name="countdown" size="3" value="15"> characters left.</font>
</form>
此解决方案仅用于限制使用Java Script的文本框中的字符数。
答案 1 :(得分:0)
Jquery文件:
jquery.maxlength.js
/*
* jQuery Maxlength plugin 1.0.0
*
* Copyright (c) 2013 Viral Patel
* http://viralpatel.net
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/mit-license.php
*/
;(function ($)
{
$.fn.maxlength = function(){
$("textarea[maxlength], input[maxlength]").keypress(function(event)
{
var key = event.which;
//all keys including return.
if(key >= 33 || key == 13 || key == 32) {
var maxLength = $(this).attr("maxlength");
var length = this.value.length;
if(length >= maxLength)
{
event.preventDefault();
}
}
});
}
})(jQuery);
在您的主文件中
<script type="text/javascript">
$(document).ready(function($){
$().maxlength();
});
</script>