gpt4 book ai didi

javascript - HTML - <textarea> 标签的困难

转载 作者:搜寻专家 更新时间:2023-11-01 05:10:20 25 4
gpt4 key购买 nike

问题:

  1. 如果文本区域长度超过其限制,并且我们在文本中间提供输入,那么它会从末尾开始 chop 字符。但我不想要那种文本区域行为。

    我想要的是,我只想允许只占用 4000 个字符的文本区域。并且如果用户尝试输入超出不允许的额外字符。

$(document).ready(function () {
var cursorPosition=0;
var enterKey_code=0;
var maxlength=4000;
var flag=0;

function setSelectionRange(input, selectionStart, selectionEnd) {
if (input.setSelectionRange) {
input.focus();
input.setSelectionRange(selectionStart, selectionEnd);
}
else if (input.createTextRange) {
var range = input.createTextRange();
range.collapse(true);
range.moveEnd('character', selectionEnd);
range.moveStart('character', selectionStart);
range.select();
}
}

function setCaretToPos (input, pos) {
setSelectionRange(input, pos, pos);
}

$('#MaxChar').text(maxlength);

function countChar(key_event){
var text_value = $('#Comments').val();
var cursorPosition = $('#Comments').prop("selectionStart");
var len=text_value.length;

if (len > maxlength) {
flag=1;
$('#Comments').val(text_value.substring(0, maxlength));
}

$('#CurrentChar').html($('#Comments').val().length);
}

$('#Comments').keyup(function (key_event) {
countChar(key_event);

if(flag==1)
{
var c=$('#Comments');
setCaretToPos(c[0], cursorPosition+1);
flag=0;
}
});

$('#Comments').keydown(function (key_event) {
cursorPosition = $('#Comments').prop("selectionStart");
countChar(key_event);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrap">
<label id="CurrentChar">0</label> / <label id="MaxChar">0</label>
<br />
<textarea rows="20" cols="40" id="Comments"></textarea>
</div>

最佳答案

尝试使用 maxlength 的简单 HTML 解决方案

maxlength Declares an upper bound on the number of characters the user can input. Normally the UI ignores attempts by the user to type in additional characters beyond this limit.

<textarea maxlength="4000"></textarea>

有一个 jQuery 插件的替代品 jQuery Max Length

关于javascript - HTML - &lt;textarea&gt; 标签的困难,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34988072/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com