Jquery help to enforce maxlength on textarea?
当您添加属性 “maxlength” 时,Jquery 会为 textarea 强制执行 maxlength。 IE 不支持 Maxlength。如何调整我的代码以处理页面上的多个文本区域?目前
如果我将文本添加到任何文本区域,它们都会以相同的值倒计时。
jQuery:
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
$(document).ready( function () {
maxLength = $(“textarea”).attr(“maxlength”); $(“textarea”).bind(“keyup change”, function(){checkMaxLength(this.id, maxLength); } ) }); function checkMaxLength(textareaID, maxLength){ currentLengthInTextarea = $(“#”+textareaID).val().length; if (currentLengthInTextarea > (maxLength)) { // Trim the field current length over the maxlength. } |
HTML:
1
2 3 4 5 6 7 8 |
Skills:
<textarea id=”1″ maxlength=”200″ rows=”10″ cols=”60″></textarea> Postions: Comments |
- api.jquery.com/each
- keith-wood.name/maxlength.html
- Balzemonger ..每个将在哪里使用?
这是最好的解决方案!
将其放入 HTML 代码中的脚本标签
1
2 3 4 5 |
$(“textarea[maxlength]”).on(“propertychange input”, function() {
if (this.value.length > this.maxlength) { this.value = this.value.substring(0, this.maxlength); } }); |
现在使用 <textarea maxlength=”{your limit}”></textarea> 来限制 {your limit} 字符数。
- 这 maxlength 是 DOM 扩展的东西吗?还是 maxlength 是 input 和 textarea 元素的合法 javascript 属性?
解决办法在这里:
http://web.enavu.com/daily-tip/maxlength-for-textarea-with-jquery/
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
$(document).ready(function() {
$(‘textarea[maxlength]’).keyup(function(){ //check if there are more characters then allowed //and change the current text with the new text }); |
你不能用这个吗:
1
|
class=”validate[required,maxSize[50]]”
|
此解决方案用作原生 HTML 文本区域,最大长度属性
1
2 3 4 5 6 7 8 9 10 11 12 |
Var MaxLength=100;
$(‘#Selector’).keydown(function (e) { var text = $(this).val(); var chars = text.length; if (chars > MaxLength) { if (e.keyCode == 46 || e.keyCode == 8 || e.keyCode == 37 || e.keyCode == 38 || e.keyCode == 39 || e.keyCode == 40) { return true; } return false; } return true; }); |
Don’t set the Maxlength property in the server side control (asp:TextBox) as server won’t convert maxLength property to HTML markup when returning to your browser.
来源:https://www.codenong.com/15031513/