Automatically add comma for monetary values in a form? - html

Not sure if I described my question well, but basically here's what I've got right now:
$('input.number').keyup(function(event) {
// skip for arrow keys
if(event.which >= 37 && event.which <= 40) return;
// format number
$(this).val(function(index, value) {
return value
.replace(/\D/g, "")
.replace(/\B(?=(\d{3})+(?!\d))/g, ",")
;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input class="number">
Right now if you enter 1000 it will add comma like this: 1,000
What I want is the number to act as a cent.
So if I write 100 it will add a dot here: 1.00
If 1000, then 10.00
If 10000 then 100.00
If 100000 then 1,000.00
and so on.
basically I want the number to be a cent and add commas and dots with a jQuery accordingly.
But I don't want them to be submitted.
I have seen this being done in ad networks, kubikads for example.
The numbers should be submitted without commas and dots.
The jQuery code in the above code seems very confusing to me .
If anyone have a ready made script or know what to modify in the script to achieve this, I would greatly appreciate

A little dirty... but it works! You can just pop off the decimal and store it while you add the commas.
$('input.number').keyup(function(event) {
// skip for arrow keys
if(event.which >= 37 && event.which <= 40) return;
// format number
$(this).val(function(index, value) {
return value
.replace(/\D/g, "")
.replace(/^0+/,"")
.split(/(\d{0,2})$/)
.join(".")
.replace(/\B(?=(\d{3})+(?!\d))/g, ",")
.replace(/.$/,"")
});
});
$('#myform').submit(function(e) {
e.currentTarget[0].value = e.currentTarget[0].value
.replace(/\D/g, "")
console.log(e.currentTarget[0].value)
return false; // return false to cancel form action
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<form id="myform">
<input class="number">
</form>

This should do it...
var num = '132406'; /Your original unformatted number
var ret = '';
var p = 0;
for (let i = num.length; i > 0; i--) {
p = p + 1;
if (p == 3 && ret.includes('.') == false) {
ret = '.' + ret;
p = 0;
} else if (p % 3 == 0 ) {
ret = ',' + ret;
}
ret = num.substring(i - 1, i) + ret;
}
console.log(ret);

Related

How do I format a number to 2 d.p when referring to many? HTML5

So I'm trying to create a simple form once a user is logged in, a user needs to say how much they want to raise and their target number, I only want to limit it to 2 d.p. I also want to have the "$" sign in the very beginning on the left hovering but not interferring just for decoration, and fornthe sign to be persistent.
`
<p> <label>
How much are you trying to raise? <input type="number" placeholder="Enter target amount" min=1 step="any" name="target">
</label> </p>
`
Probably you look for something like that? You bind an eventListener to the input field and as soon as a number has been entered you can format the number with a regex and put a $ sign in front of it for the output.
function format1(n, currency) {
n = parseInt(n);
return currency + n.toFixed(2).replace(/./g, function(c, i, a) {
return i > 0 && c !== "." && (a.length - i) % 3 === 0 ? "," + c : c;
});
}
const i = document.getElementById('target');
i.addEventListener('keyup', function () {
var number = document.getElementById('target').value;
console.log( format1( number, '$') )
})
<p> <label>
How much are you trying to raise? <input type="number" placeholder="Enter target amount" id="target" min=1 step="any" name="target">
</label> </p>
UPDATE
Ok. I have only now realized that it is not such a simple task to put the formatted number back into the input. Because it is a formatted string. I have now once the value in the input (fromartierter string) and then I have the number in a data attribute of the input deposited. With this I work. I have added: 1. that only numbers are accepted, 2. delete key deletes 3. dollar sign is now placed with CSS in the input field. You just need to add some logic when deleting all numbers one by one, that it makes the NaN an empty string at 0 characters.
So sorry for the first too fast answer. This is already a bigger deal.
function format(n) {
n = parseInt(n);
return n.toFixed(2).replace(/./g, function(c, i, a) {
return i > 0 && c !== "." && (a.length - i) % 3 === 0 ? "," + c : c;
});
}
const i = document.getElementById('target');
i.addEventListener('keyup', function (e) {
const obj = document.getElementById('target');
const number = (obj.getAttribute('data-store'));
const keynum = window.event ? e.keyCode : e.which;
if (String.fromCharCode(keynum).replace(/[^\d]/,'') == '') {
obj.value = format( number )
}
if (e.keyCode == 8) {
let newNumber = number.substring(0, number.length - 1);
obj.setAttribute('data-store', newNumber)
obj.value = format( newNumber )
return;
}
const pressed = (String.fromCharCode(keynum))
const con = number == '0' ? pressed : number + pressed;
console.log('pair', [number, pressed, con, format( con )])
obj.value = format( con );
obj.setAttribute('data-store', con)
})
.currency {
position:absolute; margin-left: 1px; margin-top:1px;
}
.inp-amount {
padding-left: 8px;
}
<p> <label>
How much are you trying to raise?
<span class="currency">$</span>
<input data-store="0" class="inp-amount" type="text" placeholder=" Enter target amount" id="target" min=1 step="any" name="target">
</label></p>

CSS - How to put a space every 3 characters in a form input?

I have this form for registering a new account and I would like to format the phone number input to look like 911 111 111 instead of 911111111 with some sort of automatic spacing css thingy.. is it possible?
let getInput1 = document.querySelector("input")
getInput1.addEventListener("keypress", (event) =>{
if(event.key == " "){
event.preventDefault();
}
});
setInterval(() => {
/* The html reference to the phone number field */
let getInput = document.querySelector("input").value;
if(getInput.length == 9) {
let arrayNumber = [];
x = 1;
for(let index = 0; index < getInput.length; index++) {
arrayNumber[index] = getInput[index];
if(x % 3 === 0) {
arrayNumber[index] = getInput[index] + " ";
}
x++;
}
document.querySelector("input").value = arrayNumber.join("");
/* Code written by anti-Illuminati armed forces section H.K.A */
}
}, 100);
You can't do it in CSS, you need code JAVASCRIPT have given below my own

How to implement duration picker with HTML5 or/with Angular8, with hours more than 24?

I am trying to implement a control, using either
<input type="time"/>
or just with
<input type="text"/>
and implement a duration picker control which can have hours format more than 24, something like 000:00:00 or hhh:mm:ss, and no am/pm option ( The default input type for time has formats in am/pm format, which is not useful in my case).
The requirement is to be able to increase decrease the duration using up and down keys much like the default input type time of HTML.
Is there any native HTML, angular, or material component for this?
Or is there a way to achieve this using regular expression/patterns or something?
One way I can think of is to write your custom control (as also mentioned by #Allabakash). For Native HTML, The control can be something like this:
window.addEventListener('DOMContentLoaded', (event) => {
document.querySelectorAll('[my-duration-picker]').forEach(picker => {
//prevent unsupported keys
const acceptedKeys = ['Backspace', 'ArrowLeft', 'ArrowRight', 'ArrowDown', 'ArrowUp'];
const selectFocus = event => {
//get cursor position and select nearest block;
const cursorPosition = event.target.selectionStart;
"000:00:00" //this is the format used to determine cursor location
const hourMarker = event.target.value.indexOf(":");
const minuteMarker = event.target.value.lastIndexOf(":");
if (hourMarker < 0 || minuteMarker < 0) {
//something wrong with the format. just return;
return;
}
if (cursorPosition < hourMarker) {
event.target.selectionStart = 0; //hours mode
event.target.selectionEnd = hourMarker;
}
if (cursorPosition > hourMarker && cursorPosition < minuteMarker) {
event.target.selectionStart = hourMarker + 1; //minutes mode
event.target.selectionEnd = minuteMarker;
}
if (cursorPosition > minuteMarker) {
event.target.selectionStart = minuteMarker + 1; //seconds mode
event.target.selectionEnd = minuteMarker + 3;
}
}
const insertFormatted = (inputBox, secondsValue) => {
let hours = Math.floor(secondsValue / 3600);
secondsValue %= 3600;
let minutes = Math.floor(secondsValue / 60);
let seconds = secondsValue % 60;
minutes = String(minutes).padStart(2, "0");
hours = String(hours).padStart(3, "0");
seconds = String(seconds).padStart(2, "0");
inputBox.value = hours + ":" + minutes + ":" + seconds;
}
const increaseValue = inputBox => {
const rawValue = inputBox.value;
sectioned = rawValue.split(':');
let secondsValue = 0
if (sectioned.length === 3) {
secondsValue = Number(sectioned[2]) + Number(sectioned[1] * 60) + Number(sectioned[0] * 60 * 60);
}
secondsValue += 1;
insertFormatted(inputBox, secondsValue);
}
const decreaseValue = inputBox => {
const rawValue = inputBox.value;
sectioned = rawValue.split(':');
let secondsValue = 0
if (sectioned.length === 3) {
secondsValue = Number(sectioned[2]) + Number(sectioned[1] * 60) + Number(sectioned[0] * 60 * 60);
}
secondsValue -= 1;
if (secondsValue < 0) {
secondsValue = 0;
}
insertFormatted(inputBox, secondsValue);
}
const validateInput = event => {
sectioned = event.target.value.split(':');
if (sectioned.length !== 3) {
event.target.value = "000:00:00"; //fallback to default
return;
}
if (isNaN(sectioned[0])) {
sectioned[0] = "000";
}
if (isNaN(sectioned[1]) || sectioned[1] < 0) {
sectioned[1] = "00";
}
if (sectioned[1] > 59 || sectioned[1].length > 2) {
sectioned[1] = "59";
}
if (isNaN(sectioned[2]) || sectioned[2] < 0) {
sectioned[2] = "00";
}
if (sectioned[2] > 59 || sectioned[2].length > 2) {
sectioned[2] = "59";
}
event.target.value = sectioned.join(":");
}
const controlsDiv = document.createElement("div");
const scrollUpBtn = document.createElement("button");
const scrollDownBtn = document.createElement("button");
scrollDownBtn.textContent = " - ";
scrollUpBtn.textContent = " + ";
scrollUpBtn.addEventListener('click', (e) => {
increaseValue(picker);
});
scrollDownBtn.addEventListener('click', (e) => {
decreaseValue(picker);
});
picker.parentNode.insertBefore(scrollDownBtn, picker.nextSibling);
picker.parentNode.insertBefore(scrollUpBtn, picker.nextSibling);
picker.value = "000:00:00";
picker.style.textAlign = "right"; //align the values to the right (optional)
picker.addEventListener('keydown', event => {
//use arrow keys to increase value;
if (event.key == 'ArrowDown' || event.key == 'ArrowUp') {
if(event.key == 'ArrowDown'){
decreaseValue(event.target);
}
if(event.key == 'ArrowUp'){
increaseValue(event.target);
}
event.preventDefault(); //prevent default
}
if (isNaN(event.key) && !acceptedKeys.includes(event.key)) {
event.preventDefault(); //prevent default
return false;
}
});
picker.addEventListener('focus', selectFocus); //selects a block of hours, minutes etc
picker.addEventListener('click', selectFocus); //selects a block of hours, minutes etc
picker.addEventListener('change', validateInput);
picker.addEventListener('blur', validateInput);
picker.addEventListener('keyup', validateInput);
});
});
<input type="text" my-duration-picker></input>
Tested and working on Google Chrome 78. I will do a Angular version later.
For the Angular version, you can write your own custom Directive and just import it to your app-module-ts declarations. See this example on stackblitz:
App Demo: https://angular-xbkeoc.stackblitz.io
Code: https://stackblitz.com/edit/angular-xbkeoc
UPDATE: I developed and improved this concept over time. You can checkout the picker here 👉 https://nadchif.github.io/html-duration-picker.js/
checkout this solution , https://github.com/FrancescoBorzi/ngx-duration-picker. which provides options you are looking for.
here is the demo - https://embed.plnkr.co/1dAIGrGqbcfrNVqs4WwW/.
Demo shows Y:M:W:D:H:M:S format. you can hide the parameters using flags defined in docs.
Since you are looking for duration picker with single input, creating your own component will be handy.
You can consider the concepts formatters and parsers.
checkout this topics which helps you in achieving that.
https://netbasal.com/angular-formatters-and-parsers-8388e2599a0e
https://stackoverflow.com/questions/39457941/parsers-and-formatters-in-angular2
here is the updated sample demo - https://stackblitz.com/edit/hello-angular-6-yuvffz
you can implement the increase/decrease functionalities using keyup/keydown event functions.
handle(event) {
let value = event.target.value; //hhh:mm:ss
if(event.key === 'ArrowUp') {
console.log('increase');
} else if (event.key === 'ArrowDown') {
console.log('decrease');
} else {
//dont allow user from entering more than two digits in seconds
}
}
Validations you need to consider ::
- If user enters wrong input, show error message / block from entering anything other than numbers
- allowing only unit specific digits - (Ex :: for hr - 3 digits, mm - 2 digits etc as per your requirement)
To do something more interesting or make it look like interactive you can use the
flipclock.js which is very cool in looking and to work with it is also feasible.
Here is the link :-
http://flipclockjs.com/
You can try with number as type :
<input type="min" min="0" max="60">
demo :
https://stackblitz.com/edit/angular-nz9hrn

How do I restrict "+ - e , ." from HTML number input?

I've got a HTML number input element: <input type="number">.
Problem is that I can also input following characters: + - e E , . which I don't want the user to be able to write.
How do I restrict these?
Edit: Boris K has got an even better answer.
Original answer:
This would be a way to accomplish that:
var ageInput = document.getElementById("age")
ageInput.addEventListener("keydown", function(e) {
// prevent: "e", "=", ",", "-", "."
if ([69, 187, 188, 189, 190].includes(e.keyCode)) {
e.preventDefault();
}
})
<input type="number" id="age">
You shouldn't rely only on <input type="number">, because that would work only in moderns browsers with different behaviours depending on the browser.
Use jQuery to perform additional checks (with a regexp):
$('#my-input').keypress(function() {
var inputValue = $(this).val();
var reg = /^\d+$/;
if (reg.test(inputValue)){
alert("input value is integer");
} else {
alert("input value is not an integer");
}
});
To restrict those values, catch the keypress event with javascript, and prevent those characters from being entered.
We capture the keyCode from the event, and restrict the input to not allow those characters by their ASCII codes.
document.getElementById('my-number-input').onkeypress = function(e) {
if(!e) e = window.event;
var keyCode = e.keyCode || e.which;
if(!((keyCode >= 48 && keyCode <= 57) ||
(keyCode >=96 && keyCode <= 105))) {
e.preventDefault(); //This stops the character being entered.
}
}
The IF statement above states that if the keycode is not in the range of 0-9 on the keyboard (including the number pad), then do not add the character to the input.

Texbox restrict characters and symbols and only allow numeric values with only one decimal point

Texbox restrict entering characters and symbols and only allow numeric values with only one decimal point.maximum length 4 and one value after decimal point.For eg: .2,12.3,1444
Here is the code in html to allow only one decimal point in a textbox:
<script type="text/javascript" language="javascript">
function isNumberKey(evt) {
var charCode = (evt.charCode) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode != 46)
return false;
else {
var input = document.getElementById("txtChar").value;
var len = document.getElementById("txtChar").value.length;
var index = document.getElementById("txtChar").value.indexOf('.');
if (index > 0 && charCode == 46) {
return false;
}
if (index >0 || index==0) {
var CharAfterdot = (len + 1) - index;
if (CharAfterdot > 2) {
return false;
}
}
if (charCode == 46 && input.split('.').length >1) {
return false;
}
I want to done this in asp.net using c#.This code is not properly working in asp.net.
Please Check this Link - Validate Input Field which will allows Only Float...
$(function(){
$('.float-input').keyup(function(e){
var entered_value = $(this).val();
var regexPattern = /^\d{0,8}(\.\d{1,2})?$/;
//Allow only Number as well 0nly 2 digit after dot(.)
if(regexPattern.test(entered_value)) {
$(this).css('background-color', 'white');
$('.err-msg').html('');
} else {
$(this).css('background-color', 'red');
$('.err-msg').html('Enter a valid Decimal Number');
}
});
});