[英]How to find the amount of characters in an input tag
我需要一些幫助來查找輸入標簽中的字符數,並在有一定數量時創建警報。 就像有25個一樣,它會創建一個警報,提示“最大”。 這是它正在進行的小提琴。 這是我所擁有的-
Char.innerText = $("#input:text").val().length;
這對於我使用它的目的是很好的,但是當我嘗試在if
語句中使用Char
時,它將無法工作。
為什么不使用這個:
if ($("#input:text").val().length == 25) {
alert('MAXXX');
}
在keyup函數中添加if語句:
if ($("#input:text").val().length == 25){
alert("Too many characters.");
}
編輯:盧克只是擊敗了我,但是在JSfiddle中有放置它的地方。
正如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語句中。
另外,您應該使用輸入事件,而不是在鍵盤事件上觸發此事件,該事件也將檢測是否按下Tab鍵或其他非打印控制字符。
$('#input:text').on('input', function checkLength() {
var max = this.getAttribute('maxlength');
if (max && this.value.length == max) {
alert('max length reached');
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.