Виджет текстового поля со счетчиком введенных символов

Общие вопросы по использованию второй версии фреймворка. Если не знаете как что-то сделать и это про Yii 2, вам сюда.
Ответить
vv-off
Сообщения: 56
Зарегистрирован: 2018.01.12, 11:49

Виджет текстового поля со счетчиком введенных символов

Сообщение vv-off »

Всем привет!
Подскажите, может кто знает готовый виджет тестового поля с динамическим подсчетом сколько символов уже введено из допустимого количества?
Аватара пользователя
Dominus
Сообщения: 892
Зарегистрирован: 2013.03.14, 21:27
Откуда: Россия, Иваново
Контактная информация:

Re: Виджет текстового поля со счетчиком введенных символов

Сообщение Dominus »

Привет, не сложно и самому написать.

JS:

Код: Выделить всё

$(document).ready(function(){
    let input = $('#textarea'),
        limit = input.attr('maxLength'),
        chars = $('.chars'),
        left = $('.left'),
        msg = $('.msg-limit'),
        cssSuccessClass = 'success',
        count = input.val().length,
        num = limit - count;
        
    chars.text(count);
    left.text(num);
    
    input.keyup(function(){       
        count = $(this).val().length;
        num = limit - count;
        
        chars.text(count);
        left.text(num);
        
        if(num > 0){
            msg.text('');
            $(this).removeClass(cssSuccessClass);            
        } else {           
            msg.text('Достигнут лимит в ' + limit + ' символов.');
            $(this).addClass(cssSuccessClass);
        }        
    });
});
HTML:

Код: Выделить всё

<textarea id="textarea" class="textarea" rows="10" cols="45" name="text" maxlength="20"></textarea>
<div>
    Введено: <span class="chars"></span><br>
    Осталось: <span class="left"></span><br>
    <span class="msg-limit""></span>
</div>
Не спорь с дураком, иначе окружающие не правильно поймут кто из вас дурак!
unknownby
Сообщения: 749
Зарегистрирован: 2019.11.05, 16:34
Контактная информация:

Re: Виджет текстового поля со счетчиком введенных символов

Сообщение unknownby »

Есть еще вариант, я когда-то искал и нашел JS-ку

Код: Выделить всё

/**
 *
 * jquery.charcounter.js version 1.2
 * requires jQuery version 1.2 or higher
 * Copyright (c) 2007 Tom Deater (http://www.tomdeater.com)
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 */

(function($) {
	/**
	 * attaches a character counter to each textarea element in the jQuery object
	 * usage: $("#myTextArea").charCounter(max, settings);
	 */

	$.fn.charCounter = function (max, settings) {
		max = max || 100;
		settings = $.extend({
			container: "<em></em>",
			classname: "charcounter",
			format: "(%1/"+max+")",
			pulse: true,
			delay: 0
		}, settings);
		var p, timeout;

		function count(el, container) {
			el = $(el);
			if (el.val().length > max) {
			    el.val(el.val().substring(0, max));
			    if (settings.pulse && !p) {
			    	pulse(container, true);
			    };
			};
			if (settings.delay > 0) {
				if (timeout) {
					window.clearTimeout(timeout);
				}
				timeout = window.setTimeout(function () {
					container.html(settings.format.replace(/%1/, (max - el.val().length)));
				}, settings.delay);
			} else {
				container.html(settings.format.replace(/%1/, (max - el.val().length)));
			}
		};

		function pulse(el, again) {
			if (p) {
				window.clearTimeout(p);
				p = null;
			};
			el.animate({ opacity: 0.1 }, 100, function () {
				$(this).animate({ opacity: 1.0 }, 100);
			});
			if (again) {
				p = window.setTimeout(function () { pulse(el) }, 200);
			};
		};

		return this.each(function () {
			var container;
			if (!settings.container.match(/^<.+>$/)) {
				// use existing element to hold counter message
				container = $(settings.container);
			} else {
				// append element to hold counter message (clean up old element first)
				$(this).next("." + settings.classname).remove();
				container = $(settings.container)
								.insertAfter(this)
								.addClass(settings.classname);
			}
			$(this)
				.unbind(".charCounter")
				.bind("keydown.charCounter", function () { count(this, container); })
				.bind("keypress.charCounter", function () { count(this, container); })
				.bind("keyup.charCounter", function () { count(this, container); })
				.bind("focus.charCounter", function () { count(this, container); })
				.bind("mouseover.charCounter", function () { count(this, container); })
				.bind("mouseout.charCounter", function () { count(this, container); })
				.bind("paste.charCounter", function () {
					var me = this;
					setTimeout(function () { count(me, container); }, 10);
				});
			if (this.addEventListener) {
				this.addEventListener('input', function () { count(this, container); }, false);
			};
			count(this, container);
		});
	};

})(jQuery);
Использование во вьюхе

Код: Выделить всё

<?php Script::begin(); ?>
<script>
    var formName = document.getElementsByTagName("form")[1].id.toLowerCase();
    $("#"+formName+"-products_code").charCounter(50);
    $("#"+formName+"-products_name").charCounter(100);
    $("#"+formName+"-products_shortname").charCounter(50);
    $("#"+formName+"-products_description").charCounter(255);
    $("#"+formName+"-products_price").charCounter(10);
    $("#"+formName+"-products_count").charCounter(10);
</script>
<?php Script::end(); ?>
vv-off
Сообщения: 56
Зарегистрирован: 2018.01.12, 11:49

Re: Виджет текстового поля со счетчиком введенных символов

Сообщение vv-off »

Спасибо за примеры!
Может кому пригодится. Нашел виджет - https://github.com/jlorente/yii2-widget ... characters
Ответить