gpt4 book ai didi

javascript - 使用 php 和 Javascript 的多个文本区域的最大长度

转载 作者:行者123 更新时间:2023-12-03 09:23:01 24 4
gpt4 key购买 nike

我正在尝试显示多个文本区域中剩余的字符数。尽管我对文本区域有不同的 ID,但仅针对第二个文本区域而不是第一个文本区域提示最大长度。我的代码如下所示

<textarea id="txtBox"></textarea> 
<input type="text" id="counterBox"/>
<script>
var txtBoxRef = document.querySelector("#txtBox");
var counterRef = document.querySelector("#counterBox");
txtBoxRef.addEventListener("keydown",function(){
var remLength = 0;
remLength = 160 - parseInt(txtBoxRef.value.length);
if(remLength < 0)
{
txtBoxRef.value = txtBoxRef.value.substring(0, 160);
return false;
}
counterRef.value = remLength + " characters remaining...";
},true);
</script>

<textarea id="txtBox1"></textarea>
<input type="text" id="counterBox1"/>
<script>
var txtBoxRef = document.querySelector("#txtBox1");
var counterRef = document.querySelector("#counterBox1");
txtBoxRef.addEventListener("keydown",function(){
var remLength = 0;
remLength = 160 - parseInt(txtBoxRef.value.length);
if(remLength < 0)
{
txtBoxRef.value = txtBoxRef.value.substring(0, 160);
return false;
}
counterRef.value = remLength + " characters remaining...";
},true);
</script>

The result is as below (What I have):

enter image description here

What I want :

enter image description here

最佳答案

看起来变量 txtBoxRefcounterRef 位于同一范围区域,您声明了两次。

<textarea id="txtBox"></textarea> 
<input type="text" id="counterBox"/>
<script>
var txtBoxRef = document.querySelector("#txtBox");
var counterRef = document.querySelector("#counterBox");
txtBoxRef.addEventListener("keydown",function(){
var remLength = 0;
remLength = 160 - parseInt(txtBoxRef.value.length);
if(remLength < 0)
{
txtBoxRef.value = txtBoxRef.value.substring(0, 160);
return false;
}
counterRef.value = remLength + " characters remaining...";
},true);
</script>

<textarea id="txtBox1"></textarea>
<input type="text" id="counterBox1"/>
<script>
var txtBoxRef1 = document.querySelector("#txtBox1");
var counterRef1 = document.querySelector("#counterBox1");
txtBoxRef1.addEventListener("keydown",function(){
var remLength = 0;
remLength = 160 - parseInt(txtBoxRef1.value.length);
if(remLength < 0)
{
txtBoxRef1.value = txtBoxRef1.value.substring(0, 160);
return false;
}
counterRef1.value = remLength + " characters remaining...";
},true);
</script>

检查Fiddle

关于javascript - 使用 php 和 Javascript 的多个文本区域的最大长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31781294/

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