How to put "-" in an form html - 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>

Related

Input[type=number] without multiple decimals

I would like to make an input[type=number] which disallows multiple decimals and all non-numbers including the letter e. The trouble is, regex that work for input[type=text] don't work for input[type=number].
When I log to console the value of a number input with multiple decimals, the value is empty.
Here is Codepen :
https://codepen.io/btn-ninja/pen/oNxRoJN?editors=1111
HTML
<input type="number"
class="isDecimal"
placeholder="Type 2.3.4 and watch console"
maxlength="20">
JS
$('.isDecimal').on("input", function(e) {
var num = $(this).val().toString();
console.log(num);
});
let lastValidInputValue;
let selectedDot = false;
const onKeypress = (e) => {
if (e.key === "." && e.target.value.indexOf(".") !== -1 && !selectedDot) e.preventDefault();
selectedDot = false;
if (e.key === "e") e.preventDefault();
};
const onInput = (e) => {
if (
e.target.value.indexOf(".") < e.target.value.length - e.target.getAttribute("data-toFixed") - 1 &&
e.target.value.indexOf(".") !== -1
) {
let newValue;
newValue = e.target.value.slice(
0,
e.target.value.indexOf(".") +
parseInt(e.target.getAttribute("data-toFixed")) +
1
);
newValue = parseFloat(newValue);
e.target.value = newValue;
}
if (e.target.value !== "") {
lastValidInputValue = e.target.value;
} else if (e.inputType.match(/delete/g)) {
lastValidInputValue = "";
} else {
e.target.value = lastValidInputValue;
}
};
const onSelect = (e) => {
if(window.getSelection().toString().indexOf(".") > -1) selectedDot = true;
}
<input type="number" id="myNumber" name="myNumber" data-toFixed="2" step="any" onkeypress="onKeypress(event)" oninput="onInput(event)" onselect="onSelect(event)">
this original posted in this question

Allow only numeric with dot separated values in textbox

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>

Disable multiple Textboxes When i click a checkbox in HTML

<input type='checkbox' name='chk1' value='1'
onclick='enable_txtbox("item","item1")'>name<br>
<input type='text' name='name1' id='item' disabled='disabled'><input type='text'
name='name1' id='item1' disabled='disabled'><input type='text' name='name1' id='item2'
disabled='disabled'>
<script>
function enable_txtbox(id,id1)
{if(document.getElementById(id).disabled == true)
{
document.getElementById(id).disabled = false;
} else
{document.getElementById(id).disabled = true; }
return true;}
</script>
use this:
<script>
function enable_txtbox(id, id1) {
var a =(document.getElementsByName("name1"));
for(var i=0;i<a.length;i++){
var b=a[i].id;
if(document.getElementById(b).disabled == true)
{
document.getElementById(b).disabled = false;
}
else
{
document.getElementById(b).disabled = true;
}
}
return true;
}
</script>

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