Live textarea character counter with jQuery

Live character counter on HTML textarea using jQuery

You most definitely have been to a website that required you to enter some text with a limited number of characters allowed in an HTML form textarea.

Such scenarios mostly happen on social media sites and business directory websites. Websites such as Facebook, Twitter and LinkedIn require you to add a short description about yourself or your business when creating or updating your social media account or business page respectively.

You probably have also noticed that these sites give you a specific maximum number of characters(spaces included) that you can include in your description e.g 500 characters, etc.

Mostly, when you start typing your description, a counter appears just below or beside the textarea. It shows you the number of characters you have already written and/or the number of characters remaining to the maximum allowed. On reaching the maximum length of characters allowed, you are not able to write anything else.

Читайте также:  Open php file with browser

In this article, you will learn why live character count is important and how you can add it to your HTML forms.

Why is live character count important?

Having the knowledge of the number of characters you have already written, and the number remaining can help you to rephrase and remove the unnecessary words and phrases early enough and avoid being caught up unaware when you reach the end without having written the most important points.

How to a character count to your HTML textarea

I will use an example to demonstrate this. I will create a simple HTML page with a textarea and use jQuery to implement the live count.

    .formdiv < width: 50%; display: block; margin: auto; margin-top: 20px; padding: 10px; box-shadow: 1px 1px 2px; border-radius: 7px; background: #f9fcfc; >.formdiv h1 < color: #06062a; font-size: 25px; border-bottom: 1px dashed #ddd; >.contact p < padding: 5px; >form < padding-bottom: 35px; >textarea < width: 98%; background: #fff; border:1px solid #eee; border-radius: 5px; padding: 5px; margin-bottom: 10px; >#written,#remaining 
Sample Form

Describe yourself in 500 characters or less

Copy-paste the above code and save it as an HTML file then open it with a web browser on your device. It will look like below and will display character count in real-time as you continue to type in the textarea.

Live HTML textarea character counter

Breaking the code down

HTML code

     
Sample Form

Describe yourself in 500 characters or less

The above HTML code creates the structure of the web page, with a heading, paragraph, and the textarea to input the texts.

In the textarea, we have set the «maxlength» attribute to 500 to prevent writing any more characters after 500 length is reached.

We have also set the «id» attribute to «description«, which we will use to identify the textarea in jQuery code.

We also added two paragraphs without any content in them, which we will use in displaying the number of characters written and the other, the number of characters remaining. The paragraph with the id attribute «written» will display the number of characters already written. The paragraph with the id attribute «remaining» will show the number of characters remaining.

CSS code

We have used CSS to style the HTML page to look more attractive and organized.

 .formdiv < width: 50%; display: block; margin: auto; margin-top: 20px; padding: 10px; box-shadow: 1px 1px 2px; border-radius: 7px; background: #f9fcfc; >.formdiv h1 < color: #06062a; font-size: 25px; border-bottom: 1px dashed #ddd; >.contact p < padding: 5px; >form < padding-bottom: 35px; >textarea < width: 98%; background: #fff; border:1px solid #eee; border-radius: 5px; padding: 5px; margin-bottom: 10px; >#written,#remaining 

jQuery code

We have used the jQuery code to count the number of characters written, calculate the number of characters remaining and display them in real-time as one continues to type.

The line below imports/adds the jQuery library to the page. Any jQuery code in the page should be written after this line in order to work. You can as well download it and host it in your project then change the src attribute to the relative path to the file.

$(function()<>) is the shortform of $(document).ready(function()<>). It is used to initialize jQuery after the other page elements have loaded. We put all our jquery code inside its curly braces.

We have set an integer value(500) as the maximum length to use in our jquery code and assigned it to a variable maximumlength as shown below:

keyup(function()<>) defines what we want to do when the on keyup event is triggered. We add all our code within its curly braces on what we would want to happen when the event is triggered.

In jquery, we use .val() to get the value of an input. In this case, $(this).val() is just the same as $(«#description»).val() and returns the value of the specified input filed which in this case is the text area.

To get the length of a string in jquery, we use the «.length» as shown below:

So in this case, we get the current length of characters entered in the textarea as below:

Since now we already have the maximum length and the current length of text entered, we can get the remaining characters by subtracting the two as below:

To add or update the content of an HTML element using jQuery, we use «.html()» after the identifier and pass the content inside the brackets ().

So to display the characters written, and the characters remaining in the empty paragraphs elements that we created, we will just use their respective id attribute values as the identifiers and the count content using .html().

You don’t have to show both. Just choose one of them. I have shown both just for demonstration purposes.

Conclusion

Live character count is a great way to help people know the number of characters remaining when writing to input fields with a limited number of characters allowed.

In this article, you have learned everything you need to know to add a real-time character counter to your HTML form textareas.

You have learned how to show the number of characters already written, and the number of characters remaining.

Источник

Работа с Textarea jQuery

Сборник jQuery приёмов с textarea – получить содержимое, вставить значение, подсчет количества символов и строк и т.д.

Во всех примерах используется следующий HTML код:

Получить содержимое Textarea

Получить строчку из Textarea

Метод split() разбивает строку на массив по регулярному выражению, в данном случае по переносу строк. Нумерация индексов массива начинается с 0.

function get_line(value, line) < var lines = value.split(/[\r\n]+/); return lines[line]; >alert(get_line($('#textarea').val(), 1)); // Выведет значение 2-й строки. 

Вставить значение в Textarea

Добавление строк в начало и конец

Для удаления лишних переносов начале и конце значения textarea используется jQuery метод $.trim() .

// Добавить текст в начало. $('#textarea').val($.trim('Текст в начале.' + '\n' + $('#textarea').val())); // Добавить текст в конец. $('#textarea').val($.trim($('#textarea').val() + '\n' + 'Текст в конце.'));

Очистить поле

Фокусировка

Установить фокус

Обработка смены фокуса Textarea

// Событие когда textarea получил фокус. $('#textarea').focus(function()< alert('Фокус установлен'); >); // Когда textarea теряет фокус. $('#textarea').blur(function()< alert('Фокус снят'); >);

Выделение текста в текстовом поле

Заблокировать и разблокировать

// Заблокировать $('#textarea').prop('disabled', true); // Разблокировать $('#textarea').prop('disabled', false);

Подсчет количества символов

JS свойство length возвращает количество символов для строк и количество элементов для массивов. Перенос строки считается как отдельный символ, для символа эмодзи length возвращает как минимум 2.

$('#textarea').bind('input', function()< $('#result').html($(this).val().length); >);

Подсчет количества строк

$('#textarea').bind('input', function()< $('#result').html($(this).val().split('\n').length); >);

Принудительный регистр вводимого текста

// Строчные $('#textarea-1').bind('input', function()< $(this).val($(this).val().toLowerCase()); >); // Заглавные $('#textarea-2').bind('input', function()< $(this).val($(this).val().toUpperCase()); >);

Определить есть ли вертикальный скролл

Свойство scrollHeight возвращает значение высоты контента в элементе, включая скрытые области из-за прокрутки, а также padding элемента, но не margin.

innerHeight() возвращает высоту элемента без учета границ.

$('#textarea').on('input', function(e) < if (this.scrollHeight >$(this).innerHeight()) < $('#result').html('Есть'); >else < $('#result').html('Нет'); >>);

Отправить значение textarea через ajax

$('#textarea').bind('input', function()< $.ajax(< url: '/ajax.php', method: 'post', dataType: 'html', data: , success: function(data) < $('#result').html(data); >>); >);

Источник

How to Get the Value of a Textarea using jQuery

Add a button below the textarea to send the text to the server when it is clicked. You can get the text using the val() method. You should first get the textarea element by id (or any else method you desire) and then call the val() method on it.

html> html> head> title>Title of the Document title> script src="https://code.jquery.com/jquery-3.5.0.min.js"> script> head> body> p>Type in the textarea and click the button to see the result. p> textarea id="comment" rows="5" cols="40"> textarea> div> button type="button">Get Value button> div> script> $(document).ready(function( ) < $("button").click(function( ) < let comment = $.trim($("#comment").val()); if(comment != "") < alert(comment); > >); >); script> body> html>

The val() Method

The val() method is a built-in jQuery method which is used to returns or set the value of an attribute for the selected elements. This method applies to the HTML form elements. It is primarily used to get the values of form elements such as input, select and textarea . When the method is called on an empty collection, it will return undefined.

Источник

Set or update value of textarea with JavaScript/jQuery

This post will discuss how to set or update the value of textarea in JavaScript and jQuery.

1. Using JavaScript

With plain JavaScript, you can use either innerHTML , innerText or textContent to write text inside a textarea.

JS

HTML

The innerText property will escape the specified text so that it will render correctly in HTML.
The innerHTML property won’t escape the text, which can lead to XSS attacks.
The textContent property offers better performance since its value is not parsed as HTML, and it also prevents XSS attacks.

2. Using jQuery

With jQuery, you can use the .text() method to replace the textarea’s text.

JS

HTML

Alternatively, you can use jQuery’s .html() method, which uses the browser’s innerHTML property to replace textarea content with the new content completely.

Another good solution is to use the .val() method to set the text value of the textarea element.

JS

HTML

To insert text at the end of a textarea, you can use the .append() method:

JS

HTML

That’s all about setting or updating the value of textarea in JavaScript and jQuery.

Average rating 4.52 /5. Vote count: 31

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Tell us how we can improve this post?

Thanks for reading.

Please use our online compiler to post code in comments using C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.

Like us? Refer us to your friends and help us grow. Happy coding 🙂

This website uses cookies. By using this site, you agree to the use of cookies, our policies, copyright terms and other conditions. Read our Privacy Policy. Got it

Источник

Оцените статью