www.webdeveloper.com
Results 1 to 3 of 3

Thread: validating numbers

  1. #1
    Join Date
    Jan 2010
    Posts
    1

    validating numbers

    Hello,

    I'm new to javascript and I have a couple of questions about functions and events. I'm trying to use the onkeypress object event to test for numbers only in a text field. I can capture the window.event for IE browsers, but I can't seem to capture the DOM object event for other browsers. In other words, when I pass in the event object to my function, e, I can't access any of the properties, such as 'e.charCode' or 'e.which', to determine what key was pressed. Sometimes the IE window.event methods aren't accessible either. Here's some of my code:

    //test which browser is being used
    var IE = document.attachEvent ? true : false;
    var DOM = document.addEventListener ? true : false;

    function validateNumber(e) {

    var evt = window.event ? window.event : e;
    var keyCode = IE ? evt.keyCode : (evt.charCode || evt.which);

    if (keyCode > 31 && (keyCode < 48 || keyCode > 57)) {

    if (window.getSelection().length > 0 || document.getSelection().length > 0
    || document.selection.createRange().text.lenght > 0)
    evt.value = "";

    evt.cancelBubble = true;
    evt.returnValue = false;
    if (evt.preventDefault) {evt.preventDefault();}
    if (evt.stopPropagation) {evt.stopPropagation();}

    }
    }

    Might anyone have a suggestion why I can't access the charCode or which methods on my 'evt' variable when I run Firefox?

    Also, I've tried just passing in the value of a text field to test for a number, and I can't access ANY properties or methods of the parameter (i.e. value.value, value.keyCode, value.charCode), so I can test the pattern against it.

    function validateNumber(value) {

    var num_pattern = /^\d{1}$/;
    var flag = num_pattern.test(value);
    }
    called from:

    onkeypress="validateNumber(document.getElementById('id').value);"

    in my text input field.

    Any suggestions why I can't access any properties or methods of the 'value' object in this example?

    I'd greatly appreciate any suggestions or feedback.
    Thank you very much.

  2. #2
    Join Date
    Oct 2003
    Location
    Andover, UK
    Posts
    947
    Didn't have time to go into your script in-depth, but I did spot this error:

    Code:
    document.selection.createRange().text.lenght

  3. #3
    Join Date
    Apr 2003
    Location
    Netherlands
    Posts
    21,654

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles