如何查找输入标签中的字符数

How to find the amount of characters in an input tag

本文关键字:标签 字符 输入 何查找 查找      更新时间:2023-09-26

我需要一些帮助来查找输入标签中的字符数,并在有一定数量时创建警报。就像如果有 25 个,那么它会创建一个警报,上面写着"Max"。这是它正在播放的小提琴。这是我所拥有的一点点——

Char.innerText = $("#input:text").val().length;

这对于我使用它的目的来说效果很好,但是当我尝试在if语句中使用Char时,它不起作用。

在 keyup 函数中添加 if 语句:

if ($("#input:text").val().length == 25){
        alert("Too many characters.");
    }

更新的 JSFiddle

编辑:卢克只是打败了我,但有把它放在JSfiddle的地方。

为什么不使用它:

if ($("#input:text").val().length == 25) {
 alert('MAXXX');
}

正如Dave在评论中指出的那样,您需要确保将Char.innerText与字符串进行比较,因为它是文本。

以下是使用 Char.innerText 的有效 if 语句:

if (Char.innerText == "25") {
  // alert
}

或者,您可以将Char.innerText更改为整数并与 25 进行比较。

这是另一种带有事件和一些警报和输出的方法。限制为五个字符。

function textCounter2(field, counter, maxlimit) {
    if (field.value.length > maxlimit) {
        field.value = field.value.substring(0, maxlimit);
        alert('Max!');
    } else {
        document.getElementById(counter).innerText = maxlimit - field.value.length;
    }
}
<input name="test" onkeyup="textCounter2(this, 'subtitlecount_lbl', 5)" onchange="textCounter2(this, 'subtitlecount_lbl', 5)" /><br />
<span id="subtitlecount_lbl"></span> characters left

既然您已经在输入元素中使用 maxlength 属性,为什么不与此值进行比较,而不是将其硬编码到 if 语句中。

此外,与其在 keyup 事件上触发此命令,该事件还将检测 Tab 键或其他非打印控制字符的按下,不如使用输入事件。

$('#input:text').on('input', function checkLength() {
  var max = this.getAttribute('maxlength');
  if (max && this.value.length == max) {
    alert('max length reached');
  }
});