By using replace(), isNan() function
- In this approach, we are taking input from input from input filed having type text.
- On submission we are chechking whether the value is valid a valid number or not and rendering response accrodingly.
- Also, we are replacing the given value by reducing it to only numeric value.
Example : This example is the implementation of the above-explained approach.
HTML
<!DOCTYPE html> < html lang = "en" > < head > < meta charset = "utf-8" > < meta name = "viewport" content = "width=device-width, initial-scale=1" > < script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js" > </ script > </ head > < body > < center > < h1 style = "color:green;padding:13px;" > w3wiki</ h1 > < h3 > Input[type=text] allow only Numeric Value Example </ h3 > < br > < form autocomplete = "off" id = "form1" > < b >Enter 4-digit Pin:</ b > < input type = "text" name = "numonly" maxlength = "4" > < br > < br > < b >Enter passkey:</ b > < input type = "text" name = "passkey" id = "num" oninput = "return onlynum()" minlength = "2" > </ form > </ center > < script > $(function () { $("input[name='numonly']").on('input', function (e) { $(this).val($(this).val().replace(/[^0-9]/g, '')); }); }); function onlynum() { let fm = document.getElementById("form2"); let ip = document.getElementById("num"); let tag = document.getElementById("value"); let res = ip.value; if (res != '') { if (isNaN(res)) { // Set input value empty ip.value = ""; // Reset the form fm.reset(); return false; } else { return true } } } </ script > </ body > </ html > |
Output:
How to force Input field to enter numbers only using JavaScript ?
In this article, we are going to learn how can we force the Input field to enter numbers only using JavaScript.
These are the following approaches that will explain how to force input field force numbers:
Table of Content
- By using ASCII code
- By using replace(), isNan() function