0

there are many post about how to prevent an ASP textbox to accept only numbers, but could somebody give me a JS example, how to check if the entered value is between 0-100? My validator fires each time key is entered and checks if it is a number or not, but do not know how to extend it to check the final value against 0-100 range.

function onlyDotsAndNumbers(event) {
    var charCode = (event.which) ? event.which : event.keyCode
    if (charCode == 46) {
        return true;
    }
    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;

    return true;
}

Cheers A

1 Answers1

0

You need to check out the whole value of the text box.

function onlyDotsAndNumbers(event) {
    var charCode = (event.which) ? event.which : event.keyCode
    if (charCode == 46) {
        return true;
    }
    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;
    var boxValue = $(event.target).val();
    if (boxValue > 100 || boxValue < 0)
        return false;

    return true;
}
Flati
  • 188
  • 2
  • 10
  • Ahh, of course. The textbox isn't updated until after the function is run, and, therefore, the value won't be over 100 until after the code is run. What you'd need to do is to find out where in the textbox the number is being inserted, and make the value from that. Here's a link to how you can find out the caret position in the text box. http://stackoverflow.com/questions/2897155/get-cursor-position-in-characters-within-a-text-input-field – Flati Aug 28 '14 at 11:57