How to force the user to put only numbers - javascript

I want the user to only be able to use input for numbers I've tried several things like oninput="this.value = this.value.replace(/[^0-9.]/g, '') and a lot more but for example the code I sent if I type a letter and keep pressing the letter on the keyboard it won't turn it to anything, I need a code that will 100% force the user to type only numbers doesn't matter what happens. if I could put a number in the input box that the user cant delete for example 0 it will be good to.

There are a few different ways to accomplish this but one of them would be capturing the keypress itself and returning false if the input is not a number.
Also if I understand you correctly, to add a default value of "0", just define it in the input directly like value="0", or you could use a placeholder="0" if that's what you're looking for.
<input type="number" value="0" onkeydown="javascript: return event.keyCode === 8 || event.keyCode === 46 ? true : !isNaN(Number(event.key))" />

You can use <input type=...> as mentioned in the input specification.

While this wouldn't enforce the user input to numbers only, you may want to consider using the pattern attribute to leverage some built-in behaviour. If you type non-numeric characters, the text colour will turn red:
input:invalid {
color: red;
}
<input type="text" pattern="[0-9]+"/>
Then we can start looking at the constraint validation API:
The Constraint Validation API enables checking values that users have entered into form controls, before submitting the values to the server.
If you type non-numeric characters and try to submit the form, you should see a built-in tooltip displaying a custom error message:
const input = document.querySelector('input');
input.addEventListener('invalid', () => {
if (input.validity.patternMismatch) {
input.setCustomValidity('Numbers only please!!');
}
});
input:invalid {
color: red;
}
<form>
<input type="text" pattern="[0-9]+"/>
<button type="submit">submit</button>
</form>

$("#but").click(function(){
let inp_val = $("#txt").val();
if(isNaN(inp_val)){
alert("Just enter a number.");
$("#txt").val("");
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="txt">
<input type="button" value="CLICK" id="but">

Related

The input from client side should entered only digits, if is alphabets should give an error msg

Create an html page with the following form:
<form method="post" name="example" action="">
<p> Enter your name <input type="text"> </p>
<input type="submit" value="Submit Information" />
</form>
<div id="a"></div>
Add a js validation function to the form that ensures that you can only add numbers in the textbox If you enter alphabets, you should generate an error message in the given div. -->
I run the requirement successfully and I'm giving the error message when it entered alphabets. However, it's giving me the same error message when I enter digits as well. Please kindly show how the function or the window.onload should be implemented. Thank you.
My answer is down below;
window.onload = function() {
let form = document.getElementById('form_ref')
form.onsubmit = function() {
let user = form.user.value;
if (parseInt(user) !== user) {
document.querySelector('div').innerHTML = "Error! Please enter digits only!";
return false;
}
return true;
}
}
<form id="form_ref" method="post" name="example" action="">
<label for="username">User</label><input type="text" name="user" id="username" required>
<div id="a"></div>
<br>
<input type="submit" value="Submit Information" id="submit">
</form>
Your equality check parseInt(user) !== user will always return true because form.user.value is a string but parseInt(...) always returns an integer. If you want to check if the entry is an integer there are a couple ways.
You can change the input's type attribute to number to make sure only digits can be entered and then you just have to make sure it's an integer and not a decimal (type="number" still allows decimal numbers so not just digits). user will still be a string, but it's easier to check. I'd recommend using Number.isInteger(...) to do the checking:
if (!Number.isInteger(parseFloat(user))) {
If you really want to use type="text" you can iterate through user and make sure its characters are all digits:
for(let i = 0; i < user.length; i++) {
if("0123456789".indexOf(user[i]) == -1) {
document.querySelector('div').innerHTML = "Error! Please enter digits only!";
return false;
}
}
return true;
One advantage of this method is that you can make more characters available if you want to just by adding them to the string that's searched in the iteration. A disadvantage is that it's slower than the other method (the indexOf method has to iterate through the string for every character of user), but for your use case that seems irrelevant-- this function doesn't need to be called many times per second as it's a simple login type of thing, and it's client-side so you don't need to handle many instances at once. If speed is an issue you could probably make a comparison to the integer equivalencies of the characters:
if(user.charCodeAt(i) < "0".charCodeAt(0) || user.charCodeAt(i) > "9".charCodeAt(0)) {

Is it possible to detect which input field was invalid upon form submit?

Using the code below, I am able to use .on("invalid") function to detect if there was an error with a field when submitting a form. If there was an error, I then check if both the input and textarea if either of them or empty, too long or too short and add the class .error.
However I am wondering if there is any way to simplify my code so that I don't have to run additional if statements inside the function.
$("form input, form textarea").on("invalid", function(event) {
var input1 = document.getElementById('input1');
var input2 = document.getElementById('input2');
if (!input1.value || input1.value.length < 9 || input1.value.length > 69) {
input1.classList.add('error');
setTimeout(function() {
input1.classList.remove('error');
}, 500);
}
if (!input2.value || input2.value.length < 21 || input2.value.length > 899) {
input2.classList.add('error');
setTimeout(function() {
input2.classList.remove('error');
}, 500);
}
});
.error {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" id="input1" minlength="8" maxlength="70" required>
<textarea id="input2" maxlength="900" required></textarea>
<input type="submit">
</form>
Here is an example of what I am looking for, where x is the field (the input or textarea) which caused the form to be invalid.:
$("form input, form textarea").on("invalid", function(event) {
x.classList.add('error'); // variable x
setTimeout(function() {
x.classList.remove('error'); // variable x
}, 500);
});
I would ideally like to stick to JavaScript, however I appreciate that jQuery may be needed.
Here is a possible solution that doesn't exactly find the target with javascript, but uses the oninvalid event listener in html.
<input type="text" oninvalid="alert('You must fill out the form!');" required>
When the form returns invalid, instead of it being packaged as a form event, this will trigger as an input event. You can make it do whatever you like in javascript when that specific input is incorrect upon form submission.
https://www.w3schools.com/jsref/event_onsubmit.asp
The event onsubmit perhaps will be a better option. Is valid for all browsers
https://www.w3schools.com/jsref/event_oninvalid.asp
Instead, if you use oninvalid you will find problems with the Safari browser
<form onsubmit="validateForm()">
Enter name: <input type="text">
<input type="submit">
</form>
function validateForm() {
//your code here
if(validationfails){
return false; //if arrives here means the form won't be submited
}
}
I was able to solve this, particularly thanks to the suggestion by John Paul Penaloza, by using oninvalid on the input and textarea field. I called a function which then added the class .error to the input field - it does the same as the code in my question, but simpler:
function error(field) {
field.classList.add('error');
setTimeout(function() {
field.classList.remove('error');
}, 500);
}
.error {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" id="input1" oninvalid="error(this);" minlength="8" maxlength="70" required>
<textarea id="input2" oninvalid="error(this);" maxlength="900" required></textarea>
<input type="submit">
</form>
Or you can think differently and offer real time error reporting.
Add an id="myForm" to your <form> element, and then use Js in a lines of:
var allInputs = $('#myForm :input');
var inputsFuked = []
allInputs.each(function( index ) {
console.log(allInputs[index]);
$(allInputs[index]).change(function() {
if (allInputs[index].checkValidity()) inputsFuked[index]=1;
else inputsFuked[index]=0;
});
});
Here is working JSfiddle with couple of more elements without validation.
This will bind on change code to be executed every time some input changes. This is an example so it only toggles values in array. When you wanna validate, you simply check which are wrong. If you stored elements in array you could state which element. Simply switch toggle index logic to add/remove from array.
But with this contraption you can do way better, you can write instant reaction to invalid element. Instead changing index in array you could prompt alert, display error, make element red. Basically interact with the user the moment he focused out of element where he made input error instead doing it passively at some point after.

forcing focus to remain on a form text element until the value is numeric

I have a form which has input fields that expect numbers only.
I'm using javascript to validate the form when the value of the field changes.
If the value is numeric, do nothing.
If the value is not numeric, set it to zero and put focus in that text field. Essentially, I'm trying to trap the cursor in that field until a numeric value is entered. For some unknown reason, focus is not being placed on that form element. cell.focus() does not work. I've even tried document.getElementById(cel.getAttribute("ID")).focus(); What might I be doing wrong?
<html>
<head>
<script>
function NAN(cell){
if (cell.value != "") {
var re = /^(0|[1-9][0-9]*)$/;
if (re.test(cell.value) == false) {
alert('You must supply a numeric value greater than 0.');
cell.value = "0";
cell.focus();
}
}
}
</script>
</head>
<body>
<input type="text" name="num" value="" onchange="NAN(cell)"/>
</body>
</html>
Your problem is in the onchange attribute:
<input type="text" name="num" value="" onchange="NAN(cell)"/>
The value is executed as JavaScript code directly. You're passing code, not just a generic signature or prototype.
Inside those event handler snippets, there's a special object this defined, referring to the current DOM element (the input tag in this example).
(Just to mention it, there is also a second predefined object event, which most likely caused your confusion.)
As a simple fix for your issue, replace cell with this in the call and it should work:
<input type="text" name="num" value="" onchange="NAN(this)"/>
It's also important to note that you should keep in mind that this verification requires JavaScript to be executed. If it's disabled, the user might still pass any values, so you should check the value server side as well (assuming this isn't just client-only code).
As an alternative to using JavaScript, you could just use HTML5 to force a specific pattern on inputs. In this case this would be trivial to do:
<input type="text" name="num" value="" pattern="(?!0)\d+" title="Quantity">
The user won't be able to submit the form unless the pattern is validated, so there's no need to force the input focus. The pattern always has to match the full value, from beginning to the end. The title attribute is typically used to provide more information in the error popup.
There are two things done:
You have to change cell to this with onchange.
According to this question at least with Firefox setTimeout has to wrap this focus-method so that it works as expected.
And a more user-friendly approach is inserted as well at the second input-field.
Hope this example helps you:
function NAN(cell) {
if (cell.value != '') {
var re = /^(0|[1-9][0-9]*)$/;
cell.value = cell.value[0]=='0'?+cell.value:cell.value;
if (re.test(cell.value) == false) {
alert('You must supply a numeric value greater than 0.');
cell.value = '0';
setTimeout(function () {
cell.select();
cell.focus();
}, 0);
}
}
}
/*
* a more user friendly approach
*/
function NAN2(cell) {
if (cell.value != '') {
var re = /^(0|[1-9][0-9]*)$/;
cell.value = cell.value[0]=='0'?+cell.value:cell.value;
if (re.test(cell.value) == false) {
alert('You must supply a numeric value greater than 0.');
cell.value = '0';
setTimeout(function () {
cell.select();
cell.focus();
markElement(cell);
}, 0);
}
else{
tickElement(cell);
}
}
}
function tickElement(cell){
cell.setAttribute('style','border: 1px solid green');
}
function markElement(cell){
cell.setAttribute('style','border: 1px solid red');
}
<p>
Your approach(onchange):
<input type="text" name="num" value="" onchange="NAN(this)"/>
</p>
<p>
Or you can use a more user friendly approach to notify an user right now when they are tipping something wrong (onkeyup):
<input type="text" name="num" value="" onkeyup="NAN2(this)"/>
</p>

Limit the user's input in an input number to 4 digits

How can I prevent (usign maybe Angular) the user from entering more than 4 numbers in a an simple number like this one :
<input type="number">
I used ng-maxlength, and max attributes, but those attributes as specified by w3.org specs and the official website Angular, do not prevent the user from adding more numbers.
What I want is that the input stops in 4 digits, like adding in somehow a mask or something to it.
Here is a way to do it using JavaScript:
HTML
<input type="number" oninput="checkNumberFieldLength(this);">
JavaScript
function checkNumberFieldLength(elem){
if (elem.value.length > 4) {
elem.value = elem.value.slice(0,4);
}
}
I would also suggest to make use of the min and max HTML attributes for the input Number element, if it applies in your case.
JSFiddle
W3c: input Number
Well, as somebody stated above maxlength doesn't work with inputs of type number, so you can do it this way:
<input type="text" pattern="\d*" maxlength="4">
of course, this will do if it's not a requirement to have input type="number"
Using ng-pattern with a regex
\d : digits
{4} : 4 times
<input type="number" ng-pattern="/^\d{4}$/" />
I would create a function in your controller like this
angular.module("my-app", [])
.controller('my-controller', function($scope) {
$scope.checkInput = function() {
if (input.value.length > 4) {
input.value = input.value.slice(0,4);
}
});
});
Then in your view you can do something like this
<input type="number" max="9999" ng-input="checkInput()" />
Warning: The max attribute will only work for the spinner. The user will still be able to enter numbers higher than that. Here's an example
<input type="number" max="9999" />
You can do that using modernizr and jquery.
I've made an example here: https://jsfiddle.net/5Lv0upnj/
$(function() {
// Check if the browser supports input[type=number]
if (Modernizr.inputtypes.number) {
$('input[type=number]').keypress(function(e) {
var $this = $(this),
maxlength = $this.attr('maxlength'),
length = $this.val().length;
if (length >= maxlength)
e.preventDefault();
});
}
});

Why 1. returns an empty string when I try to get value of an input type number using javascript and html5?

I have a normal input as follows:
<input type="number" name="quantity" id="myInput">
If I type "1." (without the quotes of course) when I try to get the value of the input with
document.getElementById("myInput").value
Only an empty string is obtained.
Is there any other way to get the "1." input with javascript?
Edit
I am working using Polymer 1.0 and databinding, so in my example I showed using normal JavaScript syntax with the intention of finding a solution to my problem using only javascript.
I just want to know how to access a property that returns the value of the input, and which I believe should be stored in some property of the object.
If you use <input type="number"> the element is enriched with an extra attribute, valueAsNumber. So instead of
document.getElementById("myInput").value
use
document.getElementById("myInput").valueAsNumber
valueAsNumber will return NaN instead of blank if the value entered in the input not is convertable to a number. There is also a validity attribute holding information of the status of the current value, both according to the value as supposed number but also according to the number input's settings, i.e "why is the number invalid".
Fun with number inputs, try this out in various browsers :
<input type="number" name="quantity" id="myInput" ><br>
<input type="text" id="value" ><br>
<input type="text" id="valueAsNumber" ><br>
<input type="text" id="validity" ><br>
document.getElementById("myInput").onkeyup = function() {
document.getElementById("value").value = this.value;
document.getElementById("valueAsNumber").value = this.valueAsNumber;
document.getElementById("validity").value = '';
for (validity in this.validity) {
if (this.validity[validity]) {
document.getElementById("validity").value+=validity+' ';
}
}
}
actually quite informative, if you want to investigate exactly why you get an empty value back from the input -> http://jsfiddle.net/oaewv2Lr/ Have tried with Chrome, Opera and FF - Chrome seems to be the most "forgiving" browser of those three.
I found a way to get invalid values:
Focus the input.
Select its contents using execCommand().
Grab the selection using window.getSelection().
Example:
document.querySelector('input[type="submit"]').addEventListener('click', function() {
var inp= document.getElementById('myInput');
inp.focus();
document.execCommand('SelectAll');
var value = window.getSelection().toString();
document.getElementById('output').textContent = value;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" name="quantity" id="myInput">
<input type="submit">
<div id="output"></div>
It won't work if you will enter 1., as 1. is not a valid number.
Update: It seems that your use of type="number" means that certain values won't come back. You can switch it to a type="text" and do the checking yourself:
document.getElementById('mySubmit').addEventListener('click', function() {
var value = document.getElementById('myInput').value;
if ( value != parseFloat(value) )
alert('Invalid Number');
document.getElementById('myOutput').innerHTML = value;
});
<input type="text" name="quantity" id="myInput">
<input type="submit" id="mySubmit">
<div id="myOutput"></div>

Categories

Resources