www.webdeveloper.com
Results 1 to 3 of 3

Thread: Count characters in text area populated from database

  1. #1
    Join Date
    Jun 2008
    Location
    London
    Posts
    175

    Count characters in text area populated from database

    I'm using the following javascript to count the characters in several text areas and it works fine when you start typing. I now need it to count the characters when the page loads. I'm guessing I need something other than keyup and also not sure if this will work with the text area being populated from a database. Can anyone help? Thanks

    Code:
    $(document).ready(function() { 
    	$('.countThisA').keyup(function() {
    		var cs = $(this).val().length;
    		$('#countA').val(cs);
    	});
    
    
    	$('.countThisB').keyup(function() {
    		var cs = $(this).val().length;
    		$('#countB').val(cs);
    	});
    });

  2. #2
    Join Date
    Feb 2003
    Location
    Michigan, USA
    Posts
    5,774
    Sounds like a great argument for creating a jQuery plugin:

    HTML Code:
    <input type="text" id="title" class="auto-counters">
    <input type="text" id="title-counter" size="3">
    
    <input type="text" id="sub-heading" class="auto-counters" data-autocounter-id="subhead_counter">
    <input type="text" id="subhead_counter" size="3">
    
    <textarea id="body" class="auto-counters"></textarea>
    <input type="text" id="body-counter" size="3">
    
    <script>
    	(function($) {
    		$.fn.autoCounter = function() {
    			var countCharacters = function countCharacters(field) {
    				var counterId = field.getAttribute("data-autocounter-id") || field.id + "-counter";
    				var $counter = $("#" + counterId);
    
    				if (!$counter.length) {
    					throw new Error("No counter was found for Id " + counterId);
    				}
    
    				$counter.val(field.value.length);
    			};
    
    			var handleKeyUp = function handleKeyUp(event) {
    				countCharacters(this);
    			};
    
    			var handleAutoCounterDestroy = function handleAutoCounterDestroy(event) {
    				$(event.target)
    					.unbind("keyup", handleKeyUp)
    					.unbind("autoCounter:destroy", handleAutoCounterDestroy);
    			};
    
    			return this.keyup(handleKeyUp)
    				.bind("autoCounter:destroy", handleAutoCounterDestroy)
    				.each(function() {
    					countCharacters(this);
    				});
    		};
    	})(jQuery);
    
    	$(function() {
    		$(".auto-counters").autoCounter();
    	});
    </script>

  3. #3
    Join Date
    Jun 2008
    Location
    London
    Posts
    175
    Thats awesome, exactly what I was looking for! Thanks for taking the time buddy

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles