Format Number allows three digits decimals instead of two - javascript

I have created a format that allows two digits after the decimal, for example 99.99 or 55.55 etc. I would like to make it allow 99.999 instead of two. Not sure where the problem is.
function formatNumber (nStr) {
nStr = String(nStr)
nStr = nStr.replace(/\,/g, '')
nStr = trimNumber(nStr)
if ($.isNumeric(nStr)) {
nStr = String(parseFloat(nStr).toFixed(2))
nStr += ''
x = nStr.split('.')
x1 = x[0]
if (x.length > 1) {
if (x[1].length > 2) {
var thirddigit = x[1].substr(2, 1)
var addone = false
if (Number(thirddigit) >= 5) {
addone = true
}
x[1] = x[1].substr(0, 2)
if (addone) {
var y = Number(x[1]) + 1
x[1] = y
}
}
}
x2 = x.length > 1 ? '.' + x[1] : ''
var rgx = /(\d+)(\d{3})/
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2')
}
if (x.length > 1) {
if (x[1].length == 1) {
x2 = '.' + x[1] + '0'
}
if (x[1].length == 0) {
x2 = '.00'
}
} else {
if (x1 != '') {
x2 = '.00'
}
}
if (getLeft(x1 + x2, 1) == '.') {
return '0' + x1 + x2
} else {
return x1 + x2
}
} else {
return ''
}
}

I found the solution! I posted it in case anyone would have the same scenario and needs it.
function Format3DigitDecimal(e, thisobj, min, max) {
var keyCode = e.keyCode == 0 ? e.charCode : e.keyCode
var ret = ((keyCode >= 48 && keyCode <= 57) || (keyCode == 44) || (specialKeys.indexOf(e.keyCode) != -1 && e.charCode != e.keyCode))
var inStr = $(thisobj).val()
if (ret && (inStr != '' && (keyCode >= 48 && keyCode <= 57)))
{
if ((inStr.length >= max.toString().length) && ((thisobj.selectionStart - thisobj.selectionEnd) == 0))
{
ret = false
}
}
if (ret && (inStr != '' && (keyCode >= 48 && keyCode <= 57)))
{
if ((inStr.length == 3) && ((thisobj.selectionStart - thisobj.selectionEnd) == 0))
{
ret = false
}
}
return ret
}

Related

how to get multiple keyboard inputs in javaScript

I am trying to make a pong like game in html, but every time one player try to move the other movement will stop.
//javaScript
var p1axis = 40;
var p2axis = 40;
function input(event)
{
var x = event.charCode || event.keyCode;
if(x == 115)
{
p1axis += 2;
document.getElementById("p1").style.top = p1axis + "%";
}
if(x == 119)
{
p1axis -= 2;
document.getElementById("p1").style.top = p1axis + "%";
}
if(x == 108)
{
p2axis += 2;
document.getElementById("p2").style.top = p2axis + "%";
}
if(x == 111)
{
p2axis -= 2;
document.getElementById("p2").style.top = p2axis + "%";
}
}
I expect that both players will be able to play freely.
instead only one can move at once.
You can create an array and add keys as they are pressed. You will have to remove them as the key is released. Also, I just used keydown with jQuery, you can also use keydown with JavaScript.
var bKeys = [];
$('body').keydown(function(e) {
if (bKeys.includes(e.which) === false) {
bKeys.push(e.which);
}
});
$('body').keyup(function(e) {
bKeys.pop(e.which);
});
setInterval(() => {
console.log(bKeys);
}, 15);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Remember to click in the body when you run the code
var k1 = false, k2 = false, k3 = false, k4 = false;
var p1axis = 40;
var p2axis = 40;
function input(event)
{
var x = event.charCode || event.keyCode;
if(x == 115 || x == 83)
{
k1 = true;
}
if(x == 119 || x == 87)
{
k2 = true;
}
if(x == 108 || x == 76)
{
k3 = true;
}
if(x == 111 || x == 79)
{
k4 = true;
}
}
function remove(event)
{
var x = event.charCode || event.keyCode;
if(x == 115 || x == 83)
{
k1 = false;
}
if(x == 119 || x == 87)
{
k2 = false;
}
if(x == 108 || x == 76)
{
k3 = false;
}
if(x == 111 || x == 79)
{
k4 = false;
}
}
function move()
{
if(k1)
{
p1axis += 1;
document.getElementById("p1").style.top = p1axis + "%";
}
if(k2)
{
p1axis -= 1;
document.getElementById("p1").style.top = p1axis + "%";
}
if(k3)
{
p2axis += 1;
document.getElementById("p2").style.top = p2axis + "%";
}
if(k4)
{
p2axis -= 1;
document.getElementById("p2").style.top = p2axis + "%";
}
setTimeout(move, 20);
}

Making a date mask react with javascript: If i press simultaneous numbers i lost the mask

I'm trying to make a mask react date dd/mm/yyyy to a custom date input.
If i press the keys slow, the mask is setted correct dd/mm/yyyy, but supposing i press the numbers rapid, my mask is breaking
This is my component:
<DateInput
name="date"
placeholder="Data"
value={this.props.data}
dateFormat="DD/MM/YYYY"
onChange={this.props.changeDataTarefa}
animation="none"
onKeyUp={() => this.props.changeDataTarefaMask(this.fixDatePattern(this.props.data))}/>
this is my functions:
fixDatePattern(currDate) {
var currentDate = currDate;
if (currentDate){
var currentLength = currentDate.length;
var lastNumberEntered = currentDate[currentLength - 1];
}
if (!this.isNumber(lastNumberEntered) && currentDate) {
return currentDate.substring(0, currentLength - 1);
}
if (currentLength > 10) {
return currentDate.substring(0, 10);
}
let dateCountTracker = 0
if (currentLength == 1 && currentDate > 1) {
var transformedDate = "0" + currentDate + '/';
dateCountTracker = 2;
currentLength = transformedDate.length;
return transformedDate;
} else if (currentLength == 4 && currentDate[3] > 3) {
let transformedDate = currentDate.substring(0, 3) + "0" + currentDate[3] + '/';
dateCountTracker = 5;
currentLength = transformedDate.length;
return transformedDate;
} else if (currentLength == 2 && (dateCountTracker != 2 && dateCountTracker != 3)) {
dateCountTracker = currentLength;
return currentDate + '/';
} else if (currentLength == 5 && (dateCountTracker != 5 && dateCountTracker != 6)) {
dateCountTracker = currentLength;
return currentDate + '/';
}
dateCountTracker = currentLength;
return currentDate;
}
isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
Instead of using keyup, use keypress event on input. And you could also use react input mask plugin for same.
You can use below code for key press event and please check working stackblitz demo.
render() {
return (
<div>
<span>Date : </span>
<input type="text" maxLength="10" placeHolder="dd/mm/yyyy" onKeyPress={this.onKeyPress}/>
</div>
)
}
onKeyPress(e){
let input = e.target;
if(e.charCode < 47 || e.charCode > 57) {
e.preventDefault();
}
var len = input.value.length;
if(len !== 1 || len !== 3) {
if(e.charCode == 47) {
e.preventDefault();
}
}
if(len === 2) {
input.value += '/';
}
if(len === 5) {
input.value += '/';
}
}
You could use below react input mask plugins to achieve requirement.
imaskjs and react-input-mask

Format Input to 2 Decimals while Typing HTML/Javascript

How can I create an input field for currency? I'm looking for it to work as follows:
Initial: 0.00
Type "1": 0.01
Type "2": 0.12
Type "5": 1.25
I'm pretty new with web design, so I'm looking for a simpler solution. I saw a similar question & answer to this question with an Angular solution, but I'm unsure how to implement that into my HTML project. I have a simple folder with HTML files in it. Thanks!
A little tricky
Working Demo
document.getElementById("demo").onkeydown = function (e) {
//console.log(e.keyCode);
if (e.keyCode != 37 && e.keyCode != 39 && e.keyCode != 8 && e.keyCode != 46)
e.preventDefault();
if (e.keyCode == 8 || e.keyCode == 46) {
//If already key down (backspaceOrDel=1) then no affect
if (backspaceOrDel == 1)
e.preventDefault();
else
backspaceOrDel = 1;
return;
}
if (e.keyCode < 48 || (e.keyCode > 57 && e.keyCode <96) || e.keyCode > 105 )
return;
try {
var val = this.value;
var val1 = 0;
if (val == 0) {
val1 = e.key / 100;
}
else {
//very tricky. We needed val1=val*10+e.key but it does not
//work correctly with floats in javascript.
//Here you have to different than android in logic
var val1 = parseFloat(val) * 1000;
val1 += parseFloat(e.key);
val1 = val1 / 100;
}
val1 = val1.toFixed(2);
if (!isNaN(val1))
this.value = val1;
}
catch (ex) {
alert("Invalid Amount");
}
};
<style>
.amount_tendered {
text-align: right;
font-size: 24px;
width: 200px;
}
</style>
<form>
<input class="amount_tendered" id="text" type="number" min="0" value="0.00" onkeyup="formatNum(this);" onclick="this.select(); activated();">
</form>
<script type="text/javascript">
String.prototype.splice = function(idx, rem, str) {
return this.slice(0, idx) + str + this.slice(idx + Math.abs(rem));
};
function formatNum(obj){
var str = obj.value;
switch (true){
case str.length==1:
str = '0.0' + str;
break;
case str.length==3:
str = '0' + str;
}
var indices = [];
for(var i=0; i<str.length;i++) {
if (str[i] === "." && (str.length - i)!=3) indices.push(i);
}
for(var i=0; i<indices.length;i++) {
str = str.replace('.','');
}
indices = [];
for(var i=0; i<str.length;i++) {
if (str[i] === ".") indices.push(i);
}
if (indices.length==0){
str = str.splice(str.length-2, 0, ".");
}
if (str[0]=='0' && str[1]!='.'){
str = str.replace('0','');
}
obj.value = str;
}
</script>

Validate Percentage Field

Hi I use the below code to validate a Percentage Field.
The field can accept 2 digits before decimal and 1 digit after decimal.
Values Valid are:
89, 99.9, 1.9,100.
My code is allowing till 99.9 and not 100. How to change the code to let the user enter 100 also?
function run(el, evt, DivID) {
var charCode = (evt.which) ? evt.which : event.keyCode;
var number = el.value.split('.');
var val = el.value;
var caratPos = getItemSelStart (el);
var dotPos = el.value.indexOf(".");
if(number.length>1 && charCode == 46){
return false;
}
// Added these checks to input 100 also.
**if ( val == 10 && (val.length > 1 && val.length < 3) && charCode == 48 ) {
return true;
}
if (dotPos == -1 && (val.length > 2) && String.fromCharCode(charCode) == '.') {
return false;
}**
if(dotPos == -1 && val.length > 1 && String.fromCharCode(charCode)!='.' ) {
return false;
}
if(caratPos > dotPos && (dotPos > -1 ) && number[1].length > 0 ) {
return false;
}
if(caratPos == dotPos && dotPos > 1 && number[1].length > 0) {
return false;
}
return true;
}
function getItemSelStart(o) {
if (o.createTextRange) {
var r = document.selection.createRange().duplicate();
r.moveEnd('character', o.value.length);
if (r.text == '') return o.value.length;
return o.value.lastIndexOf(r.text);
} else return o.selectionStart;
}

HTML input event called twice

I have a problem with html/javascript code, the code should format numbers taken from keyboard (1 -> 0.01, 2-> 0.12, 3->1.23 ... 6->1,234.56).
It seems that the result of substring and substr is appended twice. In debug it works fine but without debug it doesn't. (1 -> 0.011, 2->1.122, 3->112.233)
It works the same for delete or backspace.
Here is the code:
formatElementAmount = function(f, d) {
d = d.replace(/\./g, '');
d = d.replace(/\,/g, '');
d = parseFloat(d);
d = d + '';
var c = document.getElementById((f.target || f.srcElement).id);
var b = '0123456789';
var a = f.which || f.keyCode;
if (a == 13) { // keycode 13 = enter >
return false;
}
if (a == 9) { // keycode 9 == tab
return true;
}
if (a == 8 || a == 46) { // keyCode 8 == backspace, 46 == delete
if (d.length > 0) {
d = d.substring(0, d.length - 1);
c.value = '';
}
c.value = format(d);
return false;
}
if (c.value.length > 12) {
c.value = '';
c.value = format(d);
return false;
}
if (a >= 96 && a <= 105) { // 96 = numbpad 0, 105 = numpad 9
a = a - 48;
}
key = String.fromCharCode(a);
if (b.indexOf(key) == -1) {
return false;
}
if ((d.length == 0) && (key == '0')) {} else {
d = d + key;
}
c.value = '';
c.value = format(d);
return false;
};
format = function(f) {
if (f.length == 0) {
return '0.00';
}
if (f.length == 1) {
return '0.0' + f;
}
if (f.length == 2) {
return '0.' + f;
}
var a, b, c, d, e;
if (f.length > 2) {
a = '';
for (c = 0, d = f.length - 3; d >= 0; d--) {
if (c == 3) {
a += ',';
c = 0;
}
a += f.charAt(d);
c++;
}
b = '';
len2 = a.length;
for (d = len2 - 1; d >= 0; d--) {
b += a.charAt(d);
}
e = f.substr(f.length - 2);
b += '.' + e;
}
return b;
};
<input id="paymentForm" name="paymentForm" type="text" value="0.00" onkeydown="if(this.value =='') this.value ='0.00';
if (!formatElementAmount(event, this.value)) {
event.stopPropagation();
}"></input>
The problem with your current code is it doesn't prevent the default action of the keyDown event:
if (!formatElementAmount(event, this.value)) {
event.stopPropagation();
event.preventDefault();
}
First of all your should stop using event.stopPropagation() - it doesn't stop default event. Also don't use event.preventDefault() which is not recommended. Instead use return false which disable default event effect and stop insert chars from keyboard.
Also use keypress event instead of keydown (I can't explain why it works because I don't know).
<input id="paymentForm" name="paymentForm" type="text" value="0.00" onkeypress="if(this.value =='') this.value ='0.00';
if (!formatElementAmount(event, this.value)) {
return false;
}"></input>
I tested this fix in Firefox, IE10 & Edge which i actually have on my computer.

Categories

Resources