Shital Kadam
Shital Kadam

Reputation: 238

Don't allow the user to enter numbers greater than 12

I have an HTML textbox as:

<input style="width: 13%; height: 25%" name="txthour" id="txthour" onkeypress="return isNumberKey(event)">

I want user to stop if they enter a number greater than 12.

When the user has entered 1, I don't want to them to enter the number 3, this will prevent the number becoming 13 (which is greater than 12).

I am dong this in Javascript as:

function isNumberKey(e) {

        if (isNaN($("#txthour").val()))
        {
            alert("Enter only numbers");
        }

        if ($("#txthour").val() > 12) {

            e.cancel;
        }

        }

But it's not cancelling the text if it enters 13.

Upvotes: 2

Views: 11119

Answers (5)

Nelson Machado
Nelson Machado

Reputation: 16

The problem:

When the user types a value and you are listening to the onkeypress event, you want to be able to see what the resulting value would be so that you can compare that new value to some other value and then determine if you want to block that input via event.preventDefault() method.

Heres my solution:

1) calculate the "true" new value(now unlike most answers that were previously written that make a huge erroneous assumption "My user will only type a value at the very end of the input field"), I will take into consideration the fact that a user can actually select existing input and overwrite it...ie [before key press] inputField = "12345", user selects "12345" and presses the key for "5", so that would mean that the new value is "5", or if the user selected "234" and pressed the key for "5", the resulting value would be "155".

2) once you have the final "true" value, you can now use the isNaN() method to test if the final value is a valid number or you could just pass the final value to your own method to make whatever comparison you need and decide stop the event by calling event.preventDefault() method. here's a sample code for achieving that.

    $(document).keypress(function(event)
    {
    //this is just a container object for readability purposes
    let eventData = {
        element: null,
        userinput: "",
        fieldname: "",
        fieldValue: null,
        selectionStart: -1,
        selectionEnd: -1
    }

    eventData.fieldName = event.target.id;
    eventData.element = document.getElementById(eventData.fieldName);
    eventData.fieldValue = element.value; //holds the value before modification
    eventData.input = String.fromCharCode(event.keyCode); //what ever the user typed!
    eventData.selectionStart = event.target.selectionStart;//this records
    eventData.selectionEnd = event.target.selectionEnd;//the user selection if any

    let finalValue = getFinalValue(eventData);

    if(!isNaN(finalValue)){
    //the final value is a number and can be compared to another number!
        alert("we have a number! you may proceed");
    }else {
    //stop right there mister!
        alert("You shall not pass!");
        event.preventDefault();//user input was blocked!
    }
    }); // this here marks the end of the onkeypress method,

    // and now getFinalValue(eventData) method below...
    function getFinalValue(eventData){
        let finalValue = eventData.fieldValue.substring(0,eventData.selectionStart) +
        eventData.input + eventData.fieldValue.substring(eventData.selectionEnd);

        return finalValue;
    }//end of the getFinalValue() method

Upvotes: 0

Karl-Andr&#233; Gagnon
Karl-Andr&#233; Gagnon

Reputation: 33870

Your first problem with your code is that you are binding it on keypress. That means $("#txthour").val() will not be updated before your event.

You need to know which character the user has pressed. There is a function for that: String.fromCharCode();.

To get the current character, you can use this:

var currentChar = parseInt(String.fromCharCode(e.keyCode), 10);

then you need to check if it is a number:

if(!isNaN(currentChar))

Then you need to concatenate that character to your input:

var nextValue = $("#txthour").val() + currentChar; //It's a string concatenation, not an addition

Parse the new value and check if it's less than or equal to 12. If all of these condition matches, return true.

Final code :

function isNumberKey(e) {
    var currentChar = parseInt(String.fromCharCode(e.keyCode), 10);
    if(!isNaN(currentChar)){
        var nextValue = $("#txthour").val() + currentChar; //It's a string concatenation, not an addition
        
        if(parseInt(nextValue, 10) <= 12) return true;
    }
    
    return false;
}

http://jsfiddle.net/6X9Yq/


Edit

To allow the press of the enter key, you need to check if the keycode is 13 :

function isNumberKey(e) {
    if(e.keyCode === 13) return true;
    var currentChar = parseInt(String.fromCharCode(e.keyCode), 10);
    if(!isNaN(currentChar)){
        var nextValue = $("#txthour").val() + currentChar; //It's a string concatenation, not an addition
        
        if(parseInt(nextValue, 10) <= 12) return true;
    }
    
    return false;
}

Upvotes: 7

Nick
Nick

Reputation: 481

$( "#txthour" ).keyup(function() {

    if($( "#txthour" ).val() > 12)
    {
        $( "#txthour" ).val("12");
    }
});

http://jsfiddle.net/5tjdL/

Upvotes: 0

MattD
MattD

Reputation: 4420

jQuery solution that:

1) Checks to make sure the user only inputs numbers.

2) Makes sure the number entered is 12 or lower.

3) Alerts the user based on the criteria they're not meeting, and clears the input field.

4) Also accounts for a user pasting something into the field.

$('#txthour').on('paste input', function () {
    var number = $(this).val()
    if (isNaN(number)) {
        alert("Enter only numbers.");
        $(this).val('');
    }

    if (number > 12) {
        alert("Value entered must be 12 or lower.");
        $(this).val('');
    }
});

FIDDLE

Upvotes: 0

BardMorgan
BardMorgan

Reputation: 455

Try this instead:

            function isNumberKey(e)
        {
            var exString = $('#txthour').val();
            var newString = exString + String.fromCharCode(e.keyCode);

            if (isNaN(newString))
            {
                alert("Enter only numbers");
            }

            if (newString > 12)
            {
                e.preventDefault();
            }
        }

The reason your original code doesn't work is because when the keydown event is called, the value of the text box hasn't been set yet. The code above figures out what the value will be based on your keystroke, and then checks to see if the future value will be > 12. If so, then the preventDefault() call cancels your input.

Upvotes: 0

Related Questions