troubleshooting Question

Javascript Overwriting current text values while checking for maximum character lenght

Avatar of TheUndecider
TheUndeciderFlag for United States of America asked on
3 Comments1 Solution1000 ViewsLast Modified:
I am working on an ASP page that has some javascript validation functions.
I have the following formula in the textboxes onkeypress value.

//checking that the textboxes input doesn't exceed the maximum allowed characters
function TestMaxlength(strNm,strtxtBox, MaxChr, e)
  var key
  if (window.event)
    key = event.keyCode;
    key = e.which;
var MaxTxt = MaxChr + 1
var strTxt=document.form1.elements[strtxtBox].value
 if ( key == 8 )
      if(strTxt.length > MaxChr)
            if (window.event) //IE
                  window.event.returnValue = null;        
            else //Firefox
                alert(strNm + " are limited to " + MaxTxt + " characters!");
                  MaxTxt = 0    

strNm = the textbox field type i.e.  "Last Names"
strtxtBox = the actual textbox name i.e. "txtLastName"
MaxChr = the maximum number of characters for this text box i.e. "25"
e = event

My problem is that if I am tabbing and I need to udpate the existing value of a field where such value has already the max number of characters (like the State =2 or Zip Code = 5) I can't overwrite the existing value by just typing the new state.  I need to press the backspace or the delete key first to delete the current value.  Otherwise, I get my alert, i.e. "States are limited to 2 characters" because the 2 characters are already there.

I need to be able to start typing and overwriting the existing values if the text is highlighted even if the value is already the max number of characters. I'm assuming I need to check whether the current value is highlighted first and if it is, then I am supposed to delete it at the first key stroke (regardless if the first key is the backspace or the delete key).

Any ideas?


David H.H.Lee
Digital Marketing (Hospitality)
Join our community to see this answer!
Unlock 1 Answer and 3 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 3 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros