我发现以下 JavaScript 可以对文本区域中的字符进行计数并将其显示在另一个文本框中。它非常适合我的需要,除了它使用字段名称。我的字段是数组(short_description[]
和 long_description[]
)。有没有办法使用字段 id 而不是名称?
<script>
function textCounter(field,cntfield,maxlimit) {
if (field.value.length > maxlimit) // if too long...trim it!
field.value = field.value.substring(0, maxlimit);
// otherwise, update 'characters left' counter
else
cntfield.value = maxlimit - field.value.length;
}
</script>
这是一个字段示例:
<textarea id=sd1 rows="2" name="short_description[]">
onKeyDown="textCounter(document.myForm.short_description[],document.myForm.remLen1,125)"
onKeyUp="textCounter(document.myForm.short_description[],document.myForm.remLen1,125)">
</textarea>
<br>
<input readonly type="text" name="remLen1" size="3" maxlength="3" value="125">
characters left
一如既往,任何帮助将不胜感激。
最佳答案
使用您想要的 ID 传入对 document.getElementById() 的调用。
onKeyDown="textCounter(document.getElementById('sd1'),document.myForm.remLen1,125)"
onKeyUp="textCounter(document.getElementById('sd1'),document.myForm.remLen1,125)">
关于javascript - 表单字段文本区域计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7352141/