Click here to Skip to main content
15,887,214 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
I have used a Javascript function to restrict the length of a text box to 100. The Code of java script function is given below

C#
function Max_LengthLimit_100(obj) {
   
    var testVariableLength = (obj ? obj.value.length : 0);
    if (testVariableLength > 100) {
        return false;
    }
    else {
        return true;
    }
}


I call this function as onKeyPress="javascript:return Max_LengthLimit_100(this);
Its working fine but When I leave the TextBox it produces the following Error "Microsoft Jscript runtime Error, Value.Length is null or not and object." This Error is raised in debug mode but When I publish the website it produces "Error on Page".

What changes should I made to function to avoid Error.

Thanks in Advance
Azhar
Posted
Updated 23-Aug-11 19:20pm
v2
Comments
Prerak Patel 24-Aug-11 1:20am    
Use code block for code segments.

have u develope this code in ASP.NET ? if yes then use MaxLength property of textbox. it will help you to restrict the length to 100.

otherwise here is javascript function

JavaScript
function Max_LengthLimit_100(obj)
 {
  
   if (obj.value != "")
      {
        if (value.length > 100) 
        return false;
      }

}


call this function on onkeypress="return Max_LengthLimit_100(this.id)"
 
Share this answer
 
Use (obj.value == '' ? 0 : obj.value.length); and check that you are passing the textbox object properly to the function.
 
Share this answer
 
Thanks Prerak Patel.
I have made slight Change to your Code and it work fine for me. Again thanks for your idea and help.

function Max_LengthLimit_100(obj) {
if (obj.value != "" && obj.value!=null) {
if (obj.value.length > 100)
return false;
}
}

regards
Azhar Iqbal
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900