如果用户输入超过1000个字符或复制超过1000个字符,我想显示警告消息。为此,我使用以下JS代码但不知何故它不起作用。
HTML code:
<div class="form-group">
<label for="">Werk-Beschreibung</label>
<textarea id="limit" maxlength="1000" name="werk_beschreibung" maxlength="1000" cols="30" rows="10" class="form-control"><?php echo escape($werk_beschreibung); ?></textarea><span class="counter"></span>
</div>
JS代码:
$("#limit").on('input', function() {
if($(this).val().length >=1001) {
alert('you have reached a limit of 1000');
}
});
我在这里做错了什么?
答案 0 :(得分:2)
以下是How can I bind to the change event of a textarea in jQuery?
的代码$('#textareaID').bind('input propertychange', function() {
if (this.value.length > 1000) {
$("#textareaID").val($("#textareaID").val().substring(0,1000));
alert("stop");
}
});
这是1000字符限制的工作小提琴。
答案 1 :(得分:0)
看看这个片段,你正在听错了事件。
; (function ($) {
$.fn.characterCounter = function (limit) {
return this.filter("textarea, input:text").each(function () {
var $this = $(this),
checkCharacters = function (event) {
if ($this.val().length > limit) {
// Trim the string as paste would allow you to make it
// more than the limit.
$this.val($this.val().substring(0, limit))
// Cancel the original event
event.preventDefault();
event.stopPropagation();
}
};
$this.keyup(function (event) {
// Keys "enumeration"
var keys = {
BACKSPACE: 8,
TAB: 9,
LEFT: 37,
UP: 38,
RIGHT: 39,
DOWN: 40
};
// which normalizes keycode and charcode.
switch (event.which) {
case keys.UP:
case keys.DOWN:
case keys.LEFT:
case keys.RIGHT:
case keys.TAB:
break;
default:
checkCharacters(event);
break;
}
});
// Handle cut/paste.
$this.bind("paste cut", function (event) {
// Delay so that paste value is captured.
setTimeout(function () { checkCharacters(event); event = null; }, 150);
});
});
};
}(jQuery));
$(document).ready(function () {
$("textarea").characterCounter(100);
});
textarea
{
height:300px;
width:350px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea>
</textarea>
答案 2 :(得分:0)
您的代码几乎无效,无需进行大的更改,您只需要确保maxlength
在您的情况下是相同的,一切顺利。
注意:删除maxlength="1000"
字段中重复的textarea
。
$("#limit").on('input', function() {
if ($(this).val().length >= 10) {
alert('you have reached a limit of 10');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label for="">Werk-Beschreibung</label>
<textarea id="limit" maxlength="10" name="werk_beschreibung" cols="30" rows="10" class="form-control"></textarea><span class="counter"></span>
</div>