Jquery count two text fields

Hi,

I have seen many character counter scripts (with feedback), to count the characters of a text box. However, I am trying to accomplish the same thing however need to make sure the combined value of two text boxes don’t exceed a limit. Ie… there is a visual countdown of number of characters remaining (val) of the two text boxes combined, and an error pops up if it is exceeded.

you could do something neat with a jQuery plugin:


jQuery.fn.getLength = function(){
   var l = 0;
   this.each(function(){
       l += jQuery(this).val().length;
   });
   return l;
};

var numChars = jQuery('input').getLength();
if (numChars > whatever) {
// error
}

Untested, and I think it would blow up nicely if you put anything in your selector that didn’t support .val(), but serves the purpose. You could also show visually the combined character count:


var $inputs = jQuery('#input1,#input2');
$inputs.bind('keyup',function(){
     jQuery('#yourcounthere').html($inputs.getLength());
});