gpt4 book ai didi

javascript - 多个文本区域的字数限制

转载 作者:太空宇宙 更新时间:2023-11-04 15:50:55 25 4
gpt4 key购买 nike

我正在创建一个包含四个文本区域表单的网站。每个表格都有字数限制。

  • textarea1:250 字限制
  • textarea2:500 字限制
  • textarea3:500 字限制
  • textarea4:250 字限制

我尝试使用在尝试解决此问题时发现的现有示例,但似乎没有任何效果。

   <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script>
var maxwords = 250;
//
function check_length(obj, cnt, rem)
{
var ary = obj.value.split(" "); // doubled spaces will throw this off
var len = ary.length;
cnt.innerHTML = len;
rem.innerHTML = maxwords - len;
if (len > maxwords) {
alert("Message in '" + obj.name + "' limited to " + maxwords + " words.");
ary = ary.slice(0,maxwords-1);
obj.value = ary.join(" "); // truncate additional words
cnt.innerHTML = maxwords;
rem.innerHTML = 0;
return false;
}
return true;
}

</script>

HTML

   <textarea name="Message 1" onkeypress="
return check_length(this,
document.getElementById('count1'),
document.getElementById('remaining1'));"></textarea>
Word count: <span id="count1">0</span> &nbsp;
Words remaining: <span id="remaining1">250</span>

<textarea name="Message 2" onkeypress="
return check_length(this,
document.getElementById('count2'),
document.getElementById('remaining2'));"></textarea>
Word count: <span id="count2">0</span> &nbsp;
Words remaining: <span id="remaining2">500</span>

有谁知道这个问题的解决方案吗?

提前致谢,汤姆

最佳答案

向您的函数添加一个额外的参数,并将每次函数调用的 maxWords 发送给它:

function check_length(obj, cnt, rem, maxwords)
{
//... rest of the function would stay the same

当你调用它时,包括最大字数

<textarea name="Message 2" onkeypress="
return check_length(this,
document.getElementById('count2'),
document.getElementById('remaining2'), 250);"></textarea>
Word count: <span id="count2">0</span> &nbsp;
Words remaining: <span id="remaining2">500</span>

删除剩余的单词,

function check_length(obj, cnt, maxwords)
{
var ary = obj.value.split(" "); // doubled spaces will throw this off
var len = ary.length;
cnt.innerHTML = len;

if (len > maxwords) {
alert("Message in '" + obj.name + "' limited to " + maxwords + " words.");
ary = ary.slice(0,maxwords-1);
obj.value = ary.join(" "); // truncate additional words
cnt.innerHTML = maxwords;
return false;
}
return true;
}

在您的 HTML 中,

<textarea name="Message 1" onkeypress="
return check_length(this,
document.getElementById('count1'),250);"></textarea>
Word count: <span id="count1">0</span> &nbsp;

关于javascript - 多个文本区域的字数限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11227647/

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