On Tue, Mar 10, 2009 at 7:42 PM, IanR <i...@ianroke.co.uk> wrote: > > I have got some code http://pastebin.com/mc99132c which counts how > many characters have been entered in a textbox and subtracts it from > the maxlength to show how many characters are left. > > If I add a new textbox I don't want to copy and paste the code down > and rename the variables so is there a way of navigating the DOM tree > to change just the element currently being edited? >
This works: $(document).ready(function() { $('.word_count').wordCount({alert_limit: 5}); }); jQuery.fn.wordCount = function(options) { var defaults = { alert_limit: 10 }; var opts = jQuery.extend(defaults, options); return jQuery(this).each(function() { var orig_length = jQuery(this).attr('maxlength') - jQuery(this).val().length; jQuery(this).after( '<div><span class="counter">'+orig_length+'</span> character(s) available</div>' ); jQuery(this).keyup(function() { var new_length = jQuery(this).attr('maxlength') - jQuery(this).val().length; jQuery(this).next().find('.counter').text(new_length); jQuery(this).next().find('.counter').css('color', (new_length <= opts.alert_limit ? 'red' : 'black')); }); }); }; It could probably be optimised further. I removed the counter from the markup and added it dynamically. I also put it inside a div to contain the text but if you don't want that just adjust the jQuery(this).next().find('.counter') bits. I also made the "alert_limit" no. of chars configurable (I couldn't think of another name). Note that I used "jQuery" as that's good practice with plugins. And, speaking of, there's really no need to put your scripts in the body when you have $(document).ready() available.