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;
	}
});	

However, the above code will work only with static input fields, if you want to accept only numbers on dynamically added input fields then you should check out my tutorial about it.

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

Facebook Official Page: All PHP Tricks

Twitter 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. Required fields are marked *