简体   繁体   English

如何根据文本区域长度更改文本

[英]How to change text based on textarea length

I added the following code, and I am getting the text to update, but only when clicking outside of the textarea. 我添加了以下代码,并且正在更新文本,但当在文本区域之外单击时才可以

$('.form__input-el').change(function() {
    $('.form__character-indicator').text($('.form__input-el').val().length);
})

Why is this happening and how can I make it update without clicking outside of the textarea? 为什么会发生这种情况?如何在不单击文本区域外部的情况下进行更新?

尝试input而不是change这将在用户每次输入内容时触发。

according to jQuery docs: For select boxes, checkboxes, and radio buttons, the event is fired immediately when the user makes a selection with the mouse, but for the other element types the event is deferred until the element loses focus 根据jQuery docs: For select boxes, checkboxes, and radio buttons, the event is fired immediately when the user makes a selection with the mouse, but for the other element types the event is deferred until the element loses focus

This is why your event appears only on leaving the textareas focus. 这就是为什么您的事件仅在离开文本区域焦点时出现的原因。

https://api.jquery.com/change/ https://api.jquery.com/change/

a complete list of the events can be found here: 完整的事件列表可以在这里找到:

https://api.jquery.com/category/events/ https://api.jquery.com/category/events/

so you need to use another event, maybe like: 因此您需要使用另一个事件,例如:

https://api.jquery.com/keydown/ https://api.jquery.com/keydown/

you you can use keyup if you want to get change the output immediately 如果您想立即更改输出,则可以使用keyup

 $('.form__input-el').keyup(function() { $('.form__character-indicator').text($('.form__input-el').val().length); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <textarea class="form__input-el"></textarea> <div class="form__character-indicator"></div> 

Use a keyup event to update your character count while the user is typing 使用keyup事件来更新您的字符数,而用户输入

Try something like this 试试这个

$('.textarea').on('keyup', function() {

  var newCount = $(this).val().length

 $('.count').html(newCount)

})

Here is a jsfiddle 这是一个jsfiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM