Link to home
Create AccountLog in
Avatar of rutledgj
rutledgj

asked on

javascript problem

I have the following javascript in an asp.net user control

<script type='text/javascript'> function integersOnly(sender, args) {
         if (args.get_keyCode() == 46 || args.get_keyCode() == 37 || args.get_keyCode == 39)
                     args.set_cancel(false);
         else if ((args.get_keyCode() > 31 && args.get_keyCode() < 48) ||  args.get_keyCode() == 190 ||args.get_keyCode() > 57)  
                     args.set_cancel(true);}</script>


My goal is to limit the textbox to just positive integers. That part works ok except I can't get the decimal to be disallowed while allowing the delete key. Also, I want to enable the right arrow (which I thought was keycode 39) but it doesn't work.
Avatar of rutledgj
rutledgj

ASKER

Also keycode 37 allows both left arrow and %. I don't want %
Avatar of Tom Beck
Seems like your approach is backwards. Why not just remove every character that is not a number on key up. Maybe like this:

<input type="text" id="txtInput" onKeyUp="checkChar()" />

var txtBox = document.getElementById("txtInput");
function checkChar() {
    var lastChar = txtBox.value.substring(txtBox.value.length - 1);    
    if(isNaN(lastChar)){
        txtBox.value = txtBox.value.substring(0, txtBox.value.length-1);
    }
}
I would prefer that the invalid character not show up at all
No problem.

<input style="color:#fff" type="text" id="txtInput" onKeyUp="checkChar()" onKeyDown="this.style.color='#fff'" />

var txtBox = document.getElementById("txtInput");
function checkChar() {
    var lastChar = txtBox.value.substring(txtBox.value.length - 1);    
    if(isNaN(lastChar)){
        txtBox.value = txtBox.value.substring(0, txtBox.value.length-1);
    }    
    txtBox.style.color = "#000";
}

I believe doing it this way will be more reliable than using keycodes.

http://www.quirksmode.org/js/keys.html
Does this work with an asp.net txtbox?
You're doing this client side so, yes, it will still work but you should use inline server side code to get the actual rendered id of the text box.

var txtBox = document.getElementById("<%= txtBox.ClientID %>");
I'm not really sure what you mean by the txtbox.clientid. Where do I get this from?
Also, if I want this to work with multiple textboxes do I have to define different functions?
ASKER CERTIFIED SOLUTION
Avatar of Tom Beck
Tom Beck
Flag of United States of America image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
Thanks. I have spent many hours on this.