Textbox numbers only validation JQuery

If you want to allow numbers only in text field use event.keyCode property to identify which key is clicked and based on keyCode value it prevent user to input certain characters in textbox. See below example.

Numbers only textbox

<input  type="text" class="numbers"/>

 $(".numberDec").keydown(function(event) {
                        if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode ==  13 || event.keyCode == 190 || event.keyCode == 110 || (event.keyCode == 65 && event.ctrlKey === true) || (event.keyCode >= 35 && event.keyCode <= 39) || event.keyCode == 189) {
                            return
                        } else {
                            if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)) {
                                event.preventDefault()
                            }
                        }
    })

Above code will prevent user to enter any characters/special characters on keydown.

Numbers with decimal place textbox.

This allow’s numbers including decimal places.


<input  type="text" class="numberDecimal"/>

$(".numberDecimal").keydown(function(event) {
                        if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 || event.keyCode == 190 || event.keyCode == 110 || (event.keyCode == 65 && event.ctrlKey === true) || (event.keyCode >= 35 && event.keyCode <= 39) || event.keyCode == 189) {
                            return
                        } else {
                            if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)) {
                                event.preventDefault()
                            }
                        }	
    })

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>