Insert Only Numbers Using jQuery

Demo Download

Today I want to share a validation tutorial with you, this validation will allow you to insert only numbers in the input field using jQuery.

HTML

<input type="text" name="numbers" class="numbers" placeholder="Enter Only Numbers" />

jQuery

$(".numbers").keypress(function (e) {
//if the letter is not digit then display error and don't type anything
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
//display error message
alert("Insert Only Numbers");
return false;
}
});

Query New

Below jQuery will remove all strings except numbers.

$(".numbers").on("keypress keyup blur",function (event) {    
	$(this).val($(this).val().replace(/[^\d].+/, ""));
	if ((event.which < 48 || event.which > 57)) {
		event.preventDefault();
		return false;
	}
});	

If you found this tutorial helpful so share it with your friends, developer groups and leave your comment.

Facebook Official Page: All PHP Tricks

Article By
Javed Ur Rehman is a passionate blogger and web developer, he loves to share web development tutorials and blogging tips. He usually writes about HTML, CSS, JavaScript, Jquery, Ajax, PHP and MySQL.

Leave a Reply

Your email address will not be published.