Allow only numeric with dot separated values in textbox - html

A text box must allow to enter only numbers from 0 to 9 and the maximum length of the field is 5 and the text box must accept values upto 99.99 only.

HTML INPUT TAG
<input id="input" onblur="validate(this)"/>
JAVASCRIPT
function validate(inputField)
{
if(inputField.value.length > 5)
alert("Field should be less than 5 in length");
else if(parseFloat(inputField.value) > 99.99)
alert("value should be less than 99.99");
else
this.form.submit();
}

This got the code to work:
<HTML>
<HEAD>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<SCRIPT language=Javascript>
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode != 46 && charCode > 31
&& (charCode < 48 || charCode > 57))
return false;
return true;
}
$(document).ready(function ()
{
$('#Percentage1').keyup(function (event)
{
var currentValue = $(this).val();
var length = currentValue.length;
if (length == 2)
{
$(this).val(currentValue + ".");
}
else if (length == 3)
{
$(this).val(currentValue + "");
}
});
});
</SCRIPT>
</HEAD>
<BODY>
<input class="user-reg-input fl" type="text" name="Percentage[]" id="Percentage1" value="" onpaste="return false"
onkeypress="return isNumberKey(event)" maxlength="5" />
</BODY>
</HTML>

Related

How to put "-" in an form html

I am working on a form to fill out my bank account number, so I want to put a tick. Automatically so that it can be viewed more easily
<input class="form-control" type="text" placeholder="" name="account_number">
Try this
$(document).ready(function () {
$("#txtPhoneNo").keyup(function (e) {
if($(this).val().length === 14) return;
if(e.keyCode === 8 || e.keyCode === 37 || e.keyCode === 39) return;
let newStr = '';
let groups = $(this).val().split('-');
for(let i in groups) {
if (groups[i].length % 4 === 0) {
newStr += groups[i] + "-"
} else {
newStr += groups[i];
}
}
$(this).val(newStr);
});
})
<input type='text' placeholder="please enter" id="txtPhoneNo" name='phone' maxlength='14'><BR>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

HTML input with decimal format 999,99

When I introduce 3 integer I cannot introduce nor decimal separator neither decimals until I delete some digit.
It must be in keypress and I tested with regex and everything I know aboy javascript and JQuery.
Thank you very much.
$('#calculator-input').keypress(function (event) {
var $this = $(this);
if ((event.which != 44 || $this.val().indexOf(',') != -1) &&
((event.which < 48 || event.which > 57) &&
(event.which != 0 && event.which != 8))) {
event.preventDefault();
}
var text = $(this).val();
if ((event.which == 44) && (text.indexOf(',') == -1)) {
setTimeout(function() {
if ($this.val().substring($this.val().indexOf(',')).length > 3) {
$this.val($this.val().substring(0, $this.val().indexOf(',') + 3));
}
}, 1);
}
if ((text.indexOf(',') != -1) &&
(text.substring(text.indexOf(',')).length > 2) &&
(event.which != 0 && event.which != 8) &&
($(this)[0].selectionStart >= text.length - 2)) {
event.preventDefault();
}
var calculatorInput = $('#calculator-input').val().split(",");
var integers = parseInt(calculatorInput[0], 10);
var decimals = parseInt(calculatorInput[1], 10);
if(calculatorInput[0].length >= 3) {
return false;
}
});
As far as I understood your question, you want to format the number in the input field. But how about this solution?
document.getElementById("decimal-input").onkeyup = function() {
var digits = this.value.match(/\d/g);
if(digits) {
digits = +digits.join("");
this.value = digits.toLocaleString();
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0">
</head>
<body>
<input type="text" id="decimal-input">
</body>
</html>
I'll recommend to use the keyup event but you can replace it with keypress event too. I haven't added the validation but try it out and see if it works for you.

Allow only numbers into a input text box

I have a number input text box and I want to allow the user to edit but do not want to allow the user to enter any other text except numbers. I want them only to be able to use the arrows on the number input box.
<input type = "number" min="0" max="10" step="0.5" input id="rating" name = "rating" class = "login-input" placeholder = "Rating 1-5:" value="0">
You can achieve this by pure JavaScript. Create this function that you can reuse in your script.
function allowNumbersOnly(e) {
var code = (e.which) ? e.which : e.keyCode;
if (code > 31 && (code < 48 || code > 57)) {
e.preventDefault();
}
}
You may preferably call this onkeypress event handler.
<input type="text" id="onlyNumbers" onkeypress="allowNumbersOnly(event)" />
function allowNumbersOnly(e) {
var code = (e.which) ? e.which : e.keyCode;
if (code > 31 && (code < 48 || code > 57)) {
e.preventDefault();
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
Try editing in me:
<input type="text" id="onlyNumbers" onkeypress="allowNumbersOnly(event)" />
</body>
</html>
However, I would recommend the unobtrusive style of writing JS using because it is good to keep the HTML semantic and away from pollution. You can execute the function on event handler that we would attach to this text box using vanilla JavaScript or jQuery.
function allowNumbersOnly(e) {
var code = (e.which) ? e.which : e.keyCode;
if (code > 31 && (code < 48 || code > 57)) {
e.preventDefault();
}
}
// using classic addEventListener method:
document.getElementById('onlyNumbers').addEventListener('keypress', function(e){ allowNumbersOnly(e);
}, false);
//using jQuery
$(function(){
$('#onlyNumbers2').keypress(function(e) {
allowNumbersOnly(e);
});
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<div>
Using addEventListener: <input type="text" id="onlyNumbers" />
</div>
<div>
Using jQuery: <input type="text" id="onlyNumbers2" />
</div>
</body>
</html>
To restrict every character you can just simply use e.preventDefault().
Besides, you can also use return false instead but preventDefault() is better in this case and return false should be chosen wisely. It is good to know the difference between both of them.
document.getElementById('rating').onkeypress = function() { return false; }
This will prevent the default behavior of keypresses on that element i.e. text showing up.
HTML
<input type="text" class="IntOnly">
Javascript
let ele = document.getElementsByClassName('IntOnly');
for (const e of ele) {
//e.addEventListener('change', filterNonIntOut.bind(null, e));
//e.addEventListener('paste', filterNonIntOut.bind(null, e));
e.addEventListener('input', filterNonIntOut.bind(null, e));
}
function filterNonIntOut(theTextbox) {
//console.log(ele);
let startPos = theTextbox.selectionStart;
let endPos = theTextbox.selectionEnd;
let str = theTextbox.value;
str = str.trim();
if (str == '') {
theTextbox.value = '';
return;
}
let result = "";
for (var i = 0; i < str.length; i++) {
let ch = str.charAt(i);
//console.log(ch);
if (ch === '1'
|| ch === '2'
|| ch === '3'
|| ch === '4'
|| ch === '5'
|| ch === '6'
|| ch === '7'
|| ch === '8'
|| ch === '9'
|| ch === '0'
) {
result += ch;
}
else {
startPos -= 1;
endPos -= 1;
}
}
theTextbox.value = result;
theTextbox.focus();
theTextbox.setSelectionRange(startPos, endPos);
}

How to make HTML input tag only accept numbers?

How to make HTML input tag only accept numbers?
I need to make sure that input field only takes numbers as input
value.
I want the user to be unable to type in any other characters other
than numbers.
User manually enters the number not a number scroll bar.
I am using the Meteor Js.And the code as shown below.
App.html
<head>
<title App</title>
</head>
<body>
{{> main}}
</body>
<template name="main">
<h1>Welcome to TICTACTOE App</h1>
<p><b>Layout Number :</b> <input type="text" id="no"></p>
</template>
App.js
if (Meteor.isClient)
{
Template.main.events
({
'keydown input#no' : function ()
{
// template data, if any, is available in 'this'
if (event.which == 13)
{ // 13 is the enter key event
console.log("You pressed enter key");
}
}
});
}
if (Meteor.isServer)
{
Meteor.startup(function ()
{
// code to run on server at startup
});
}
This should help you.
<input type="number" />
:)
Or Best way to use jQuery with keycodes:
jQuery("#yourInputId").keydown(function(event) {
// Allow: backspace, delete, tab, escape, enter and .
if ( jQuery.inArray(event.keyCode,[46,8,9,27,13,190]) !== -1 ||
// Allow: Ctrl+A
(event.keyCode == 65 && event.ctrlKey === true) ||
// Allow: home, end, left, right
(event.keyCode >= 35 && event.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
else {
// Ensure that it is a number and stop the keypress
if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) {
event.preventDefault();
}
}
});
See DEMO.
if you use HTML5 then
<input type="number" />
else
<script>
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : event.keyCode
return !(charCode > 31 && (charCode < 48 || charCode > 57));
}
</script>
<input type="text" onkeypress="return isNumberKey(event);">
With HTML5 it's easy:
<input type="number" />
If HTML5 is not supported use jQuery events: Live Demo
<label for="number">Number: </label>
<input type="text" name="number" id="number" />
<script>
$('#number').keydown(function(){
$(this).val($(this).val().replace(/[^\d]/,''));
$(this).keyup(function(){
$(this).val($(this).val().replace(/[^\d]/,''));
});
});
</script>
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
<input type="someid" name="number" onkeypress="return isNumberKey(event)"/>
will work only with HTML 5.
If you want it to work for older browser as well you have to take help of javascript.
Try this
<input name="amount" type="text" value="Only number in here"/>
<script>
$('input[name=amount]').keyup(function(){
$(this).val($(this).val().replace(/[^\d]/,''));
});
</script>
You can also use the pattern attribute in html5:
<input type="text" name="name" pattern="[0-9]" title="Title" />
On any input you need filter, you only need put the onkeydown="return onlynumbers(event);"
code.
This is a generic code that will work on old HTML and does not need jQuery. :)
<script type="text/javascript">
function onlynumbers(e) {
if (e.shiftKey === true ) {
if (e.which == 9) {
return true;
}
return false;
}
if (e.which > 57) {
return false;
}
if (e.which==32) {
return false;
}
return true;
}
</script>
<input type="text" onkeydown="return onlynumbers(event);">

Is there any way to prevent input type="number" getting negative values?

I want to get only positive values, is there any way to prevent it using only html
Please don't suggest validation method
Use the min attribute like this:
<input type="number" min="0">
For me the solution was:
<input type="number" min="0" oninput="this.value = Math.abs(this.value)">
Edit
As suggested on the comments with a minor change to work if 0 is the min value.
<input type="number" min="0" oninput="this.value =
!!this.value && Math.abs(this.value) >= 0 ? Math.abs(this.value) : null">
I was not satisfied with #Abhrabm answer because:
It was only preventing negative numbers from being entered from
up/down arrows, whereas user can type negative number from keyboard.
Solution is to prevent with key code:
// Select your input element.
var number = document.getElementById('number');
// Listen for input event on numInput.
number.onkeydown = function(e) {
if(!((e.keyCode > 95 && e.keyCode < 106)
|| (e.keyCode > 47 && e.keyCode < 58)
|| e.keyCode == 8)) {
return false;
}
}
<form action="" method="post">
<input type="number" id="number" min="0" />
<input type="submit" value="Click me!"/>
</form>
Clarification provided by #Hugh Guiney:
What key codes are being checked:
95, < 106 corresponds to Numpad 0 through 9;
47, < 58 corresponds to 0 through 9 on the Number Row; and 8 is
Backspace.
So this script is preventing invalid key from being entered in input.
This code is working fine for me. Can you please check:
<input type="number" name="test" min="0" oninput="validity.valid||(value='');">
Easy method:
<input min='0' type="number" onkeypress="return (event.charCode == 8 || event.charCode == 0) ? null : event.charCode >= 48 && event.charCode <= 57">
I wanted to allow decimal numbers and not clear the entire input if a negative was inputted. This works well in chrome at least:
<input type="number" min="0" onkeypress="return event.charCode != 45">
The #Manwal answer is good, but i like code with less lines of code for better readability. Also i like to use onclick/onkeypress usage in html instead.
My suggested solution does the same:
Add
min="0" onkeypress="return isNumberKey(event)"
to the html input and
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : event.keyCode;
return !(charCode > 31 && (charCode < 48 || charCode > 57));
}
as a javascript function.
As said, it does the same. It's just personal preference on how to solve the problem.
Here's an angular 2 solution:
create a class OnlyNumber
import {Directive, ElementRef, HostListener} from '#angular/core';
#Directive({
selector: '[OnlyNumber]'
})
export class OnlyNumber {
// Allow decimal numbers. The \. is only allowed once to occur
private regex: RegExp = new RegExp(/^[0-9]+(\.[0-9]*){0,1}$/g);
// Allow key codes for special events. Reflect :
// Backspace, tab, end, home
private specialKeys: Array<string> = ['Backspace', 'Tab', 'End', 'Home'];
constructor(private el: ElementRef) {
}
#HostListener('keydown', ['$event'])
onKeyDown(event: KeyboardEvent) {
// Allow Backspace, tab, end, and home keys
if (this.specialKeys.indexOf(event.key) !== -1) {
return;
}
// Do not use event.keycode this is deprecated.
// See: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
let current: string = this.el.nativeElement.value;
// We need this because the current value on the DOM element
// is not yet updated with the value from this event
let next: string = current.concat(event.key);
if (next && !String(next).match(this.regex)) {
event.preventDefault();
}
}
}
add OnlyNumber to declarations in app.module.ts and use like it like this anywhere in your app
<input OnlyNumber="true">
Just for reference: with jQuery you can overwrite negative values on focusout with the following code:
$(document).ready(function(){
$("body").delegate('#myInputNumber', 'focusout', function(){
if($(this).val() < 0){
$(this).val('0');
}
});
});
This does not replace server side validation!
Restrict the charcter (-) & (e) in type Number
<input type="number" onkeydown="return event.keyCode !== 69 && event.keyCode !== 189" />
Demo: https://stackblitz.com/edit/typescript-cwc9ge?file=index.ts
oninput="this.value=(this.value < Number(this.min) || this.value > Number(this.max)) ? '' : this.value;"
simply use min="0"
<v-text-field
v-model="abc"
class="ml-1 rounded-0"
outlined
dense
label="Number"
type="number"
min="0">
</v-text-field>
Just adding another way of doing this (using Angular) if you don't wanna dirt the HTML with even more code:
You only have to subscribe to the field valueChanges and set the Value as an absolute value (taking care of not emitting a new event because that will cause another valueChange hence a recursive call and trigger a Maximum call size exceeded error)
HTML CODE
<form [formGroup]="myForm">
<input type="number" formControlName="myInput"/>
</form>
TypeScript CODE (Inside your Component)
formGroup: FormGroup;
ngOnInit() {
this.myInput.valueChanges
.subscribe(() => {
this.myInput.setValue(Math.abs(this.myInput.value), {emitEvent: false});
});
}
get myInput(): AbstractControl {
return this.myForm.controls['myInput'];
}
<input type="number" name="credit_days" pattern="[^\-]+"
#credit_days="ngModel" class="form-control"
placeholder="{{ 'Enter credit days' | translate }}" min="0"
[(ngModel)]="provider.credit_days"
onkeypress="return (event.charCode == 8 || event.charCode == 0 ||
event.charCode == 13) ? null : event.charCode >= 48 && event.charCode <=
57" onpaste="return false">
The answer to this is not helpful. as its only works when you use up/down keys, but if you type -11 it will not work. So here is a small fix that I use
this one for integers
$(".integer").live("keypress keyup", function (event) {
// console.log('int = '+$(this).val());
$(this).val($(this).val().replace(/[^\d].+/, ""));
if (event.which != 8 && (event.which < 48 || event.which > 57))
{
event.preventDefault();
}
});
this one when you have numbers of price
$(".numeric, .price").live("keypress keyup", function (event) {
// console.log('numeric = '+$(this).val());
$(this).val($(this).val().replace(/[^0-9\,\.]/g, ''));
if (event.which != 8 && (event.which != 44 || $(this).val().indexOf(',') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
This solution allows all keyboard functionality including copy paste with keyboard. It prevents pasting of negative numbers with the mouse. It works with all browsers and the demo on codepen uses bootstrap and jQuery. This should work with non english language settings and keyboards. If the browser doesn't support the paste event capture (IE), it will remove the negative sign after focus out. This solution behaves as the native browser should with min=0 type=number.
Markup:
<form>
<input class="form-control positive-numeric-only" id="id-blah1" min="0" name="nm1" type="number" value="0" />
<input class="form-control positive-numeric-only" id="id-blah2" min="0" name="nm2" type="number" value="0" />
</form>
Javascript
$(document).ready(function() {
$("input.positive-numeric-only").on("keydown", function(e) {
var char = e.originalEvent.key.replace(/[^0-9^.^,]/, "");
if (char.length == 0 && !(e.originalEvent.ctrlKey || e.originalEvent.metaKey)) {
e.preventDefault();
}
});
$("input.positive-numeric-only").bind("paste", function(e) {
var numbers = e.originalEvent.clipboardData
.getData("text")
.replace(/[^0-9^.^,]/g, "");
e.preventDefault();
var the_val = parseFloat(numbers);
if (the_val > 0) {
$(this).val(the_val.toFixed(2));
}
});
$("input.positive-numeric-only").focusout(function(e) {
if (!isNaN(this.value) && this.value.length != 0) {
this.value = Math.abs(parseFloat(this.value)).toFixed(2);
} else {
this.value = 0;
}
});
});
Here is a solution that worked best of me for a QTY field that only allows numbers.
// Only allow numbers, backspace and left/right direction on QTY input
if(!((e.keyCode > 95 && e.keyCode < 106) // numpad numbers
|| (e.keyCode > 47 && e.keyCode < 58) // numbers
|| [8, 9, 35, 36, 37, 39].indexOf(e.keyCode) >= 0 // backspace, tab, home, end, left arrow, right arrow
|| (e.keyCode == 65 && (e.ctrlKey === true || e.metaKey === true)) // Ctrl/Cmd + A
|| (e.keyCode == 67 && (e.ctrlKey === true || e.metaKey === true)) // Ctrl/Cmd + C
|| (e.keyCode == 88 && (e.ctrlKey === true || e.metaKey === true)) // Ctrl/Cmd + X
|| (e.keyCode == 86 && (e.ctrlKey === true || e.metaKey === true)) // Ctrl/Cmd + V
)) {
return false;
}
If Number is Negative or Positive Using ES6’s Math.Sign
const num = -8;
// Old Way
num === 0 ? num : (num > 0 ? 1 : -1); // -1
// ES6 Way
Math.sign(num); // -1