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

前端 未结 6 1480
-上瘾入骨i
-上瘾入骨i 2021-01-30 04:32

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

6条回答
  •  北恋
    北恋 (楼主)
    2021-01-30 05:31

    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 .length on that string.

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

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

    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 then use .length on that string to find its length.

提交回复
热议问题