如何使用 jQuery 获取在文本框中输入的文本长度?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/815146/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:51:48  来源:igfitidea点击:

How can I get the length of text entered in a textbox using jQuery?

jquery

提问by Blankman

How can I get the length of text entered in a textbox using jQuery?

如何使用 jQuery 获取在文本框中输入的文本长度?

回答by yfeldblum

var myLength = $("#myTextbox").val().length;

回答by Jonathan Tran

If your textbox has an id attribute of "mytextbox", then you can get the length like this:

如果你的文本框有一个“mytextbox”的 id 属性,那么你可以得到这样的长度:

var myLength = $("#mytextbox").val().length;
  • $("#mytextbox")finds the textbox by its id.
  • .val()gets the value of the input element entered by the user, which is a string.
  • .lengthgets the number of characters in the string.
  • $("#mytextbox")通过其 id 找到文本框。
  • .val()获取用户输入的输入元素的值,是一个字符串。
  • .length获取字符串中的字符数。

回答by Rohith

For me its not text box its a span tag and this worked for me.

对我来说,它不是文本框,它是一个跨度标签,这对我有用。

var len = $("span").text().length;

回答by Aqib Shehzad

Below mentioned code works perfectly fine for taking length of any characters entered in textbox.

下面提到的代码非常适合获取文本框中输入的任何字符的长度。

$("#Texboxid").val().length;

$("#Texboxid").val().length;

回答by Fadid

CODE

代码

$('#montant-total-prevu').on("change", function() {

var taille = $('#montant-total-prevu').val().length;

    if (taille > 9) {

//TODO

}

});

回答by daveslab

You need to only grab the element with an appropriate jQuery selector and then the .val()method to get the string contained in the input textbox and then call the .lengthon that string.

您只需要使用适当的 jQuery 选择器获取元素,然后.val()获取包含在输入文本框中的字符串的方法,然后.length在该字符串上调用。

$('input:text').val().length

$('input:text').val().length

However, be warned that if the selector matches multiple inputs, .val()will only return the value of the firsttextbox. You can also change the selector to get a more specific element but keep the :textto ensure it's an input textbox.

但是,请注意,如果选择器匹配多个输入,.val()则只会返回第一个文本框的值。您还可以更改选择器以获得更具体的元素,但保留:text以确保它是一个输入文本框。

On another note, to get the length of a string contained in another, non-input element, you can use the .text()function to get the string and thenuse .lengthon thatstring to find its length.

另一方面,要获取包含在另一个非输入元素中的字符串的长度,您可以使用该.text()函数获取该字符串,然后.length字符串上使用来查找其长度。