0

i have a textbox and its javascript function declared as follows

<asp:TextBox ID="TextBox1" runat="server" onKeyUp="javascript:Count(this);" TextMode="Number"></asp:TextBox>

                           function Count(text) {
                               //asp.net textarea maxlength doesnt work; do it by hand
                               var maxlength = 4; //set your value here (or add a parm and pass it in)
                               var object = document.getElementById(text.id)  //get your object
                               if (object.value.length > maxlength) {
                                   object.focus(); //set focus to prevent jumping
                                   object.value = text.value.substring(0, maxlength); //truncate the value
                                   object.scrollTop = object.scrollHeight; //scroll to the end to prevent jumping
                                   return false;
                               }
                               return true;
                           }

I have also set the TextMode property of TextBox to Number, but i can still enter the Alphabet "e/E" and while entering this particular alphabet my javascript function is also not called. How should i solve this problem.

Rahul Bhat
  • 308
  • 2
  • 14

1 Answers1

0

Try this. You can use multiple data types for validating the input. And you can just use the MaxLength attribute to limit the characters to 4.

<asp:TextBox ID="TextBox1" onkeyup="checkString(this, 'INT')" MaxLength="4" runat="server"></asp:TextBox>

<script type="text/javascript">
    function checkString(inputID, inputType) {
        if (inputID.value != "") {
            if (inputType == "NUMERIC") {
                validChars = "0-9,.";
            } else if (inputType == "INT") {
                validChars = "0-9";
            } else if (inputType == "HASHTAG") {
                validChars = "a-z0-9-_#";
            } else if (inputType == "ALPHA") {
                validChars = "a-z";
            } else {
                validChars = "a-z0-9";
            }

            var regexp = new RegExp("[" + validChars + "]+", "ig");
            var matches = inputID.value.match(regexp);

            if (matches == null) {
                inputID.value = "";
            } else if (matches.length != 0) {
                inputID.value = matches.join("");
            }
        }
    }
</script>
VDWWD
  • 35,079
  • 22
  • 62
  • 79