Can't seem to get Not a Number NaN error to be replaced with a 0. Tried using rapply but not working for me.
window.onload = function () {
var first = document.getElementById('firstFieldId'),
second = document.getElementById('secondFieldId'),
third = document.getElementById('thirdFieldId'),
fourth = document.getElementById('fourthFieldId');
first.onkeyup = function () {
var value;
// Get the value and remove the commas
value = first.value.replace(/,/g, "");
// Make it a number
value = parseInt(value, 10);
// Add one to it
++value;
// Turn it back into a string
value = String(value);
// Put it in the other text box, formatted with commas
second.value = numberWithCommas(value);
};
third.onkeyup = function () {
var value;
// Get the value and remove the commas
value = third.value.replace(/,/g, "");
// Make it a number
value = parseInt(value, 10);
// Add one to it
++value;
// Turn it back into a string
value = String(value);
// Put it in the other text box, formatted with commas
fourth.value = numberWithCommas(value);
};
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
};
Made a JSFiddle http://jsfiddle.net/7r5SF/2/ - If you put a number in the first or third field, and then clear it, the second or fourth field will show up as NaN... It needs to say 0!
Any help would be great!
Replace
++value;
with
value = isNaN(value) ? 0 : value+1
JSFiddle
Related
I am trying to add the - after the second digit(date) on keypress for the date. Suppose if the user types the today s date as 24 after which - should be added and then after typing month "11" it should type - automatically.
Similarly, while backspacing/removing the character, dash to be removed.
Pattern : pattern="[0-9]{2}-[0-9]{2}-[0-9]{4}"
Function
onChangeText = (text) => {
text = text
.replace(/^[a-zA-Z\-]+$/g, '')
.replace(/^(\d\d\d\d)(\d)$/g, '$1-$2')
.replace(/^(\d\d\d\d\-\d\d)(\d+)$/g, '$1-$2')
.replace(/[^\d\-]/g, '')
}
here is you can do something like this, but you need first declare a variable and get the value after the regx. when you're done with regx then declare a varible and store the value in it then apply below logic!
Example
here we go!
let data = '123233';
let newData = ''; // declare the golbal variable to put dash
for ( let str = 0; data.length > str; ++str )
{
if( str % 2 === 0 && str !== 0) // finding even number and also zero
newData += '-',newData += data[str - 0];
else
newData += data[str]
}
console.log(newData)
apply this logic in your code, i hope you will get your expection!
Thanks!
I've got this function to modify a string to a USD-like format
function formatAmount(el){
var val = el.value;
//Only Numbers
val = val.replace(/[^0-9]/gi, '');
// Pad with Zeros
val = val.padStart(3,0);
// Value with Period
val = val.slice(0, -2) + '.' + val.slice(-2);
// Append $
val = '$' + val;
console.log( val );
//el.value = val; // Breaks??
}
<input type="text" onkeyup="formatAmount(this);" />
When formatting the value, it works just fine: Typing 12345 into the input will log $123.45. As soon as I change the value with el.value = val;, the function seems to get a little weird, and I can't quite figure out why. 12345 now returns $0123.45 if you type fast or $00123.45 if you type slowly. Why is is appending the 0's to the string when changing the field value, but not when logging it without changing?
Edit:
Based on what #Dennis mentioned, wrapping it in a typing-timeout function seems to work, as long as the timeout is sufficiently high. 10ms doesn't work, but 100ms seems to? This doesn't seem very elegant, however:
var formatTimeout = null;
function formatAmount(el){
clearTimeout(formatTimeout);
formatTimeout = setTimeout(function(){
var val = el.value;
//Only Numbers
val = val.replace(/[^0-9]/gi, '');
// Pad with Zeros
val = val.padStart(3,0);
// Value with Period
val = val.slice(0, -2) + '.' + val.slice(-2);
// Append $
val = '$' + val;
//console.log( val );
el.value = val; // Breaks??
}, 100);
}
The function gets triggered at every key press.
If you type in 12345, it will get triggered 5 times.
Here's what your value will look like if typing sufficiently slowly:
1, the function will change it to $0.01
2, it gets added at the end of the existing string to make it $0.012, which gets formatted by the function as $00.12
3, the initial string will be $00.123, and it will get formatted as $001.23.
...
The final result will be $00123.45.
There are a few ways to deal with this problem. The simplest solution would be to trim the initial 0s to keep your number clean, right before padding with zeros.
This difference between results while console.log and actually assigning the value is because the input to the formatAmount function is different each time.
When you set the value of the input field, this is what happens;
-> User enter `1`
-> formatAmount takes the value, converts it to $0.01 and *sets the value* to the input box
-> user enter `2`
-> formatAmount takes the value ($0.012), converts it to $00.12 and *sets the value* to the input box
This continues until you finish 12345 and get $00123.45. This happens because the two 0s you added in the start never vanish after the first 1 is typed.
Also, console.log works fine because everytime, the value received is 1, 12,...12345. The logic works fine for these. Only fails when you set the value back
A keyup action in javascript seems to work fine. Tested with various speeds and works like a charm. Also, try pasting numbers and use regex to remove leading 0's like
var textInput = document.getElementById('hello');
textInput.onkeyup = function (e) {
formatAmount(textInput.value);
};
function formatAmount(el){
var val = el;
//Only Numbers
val = val.replace(/[^0-9]/gi, '');
// Pad with Zeros
val = val.padStart(3,0);
// replace leading 0's
val = val.replace(/^0+/, '');
// Value with Period
val = val.slice(0, -2) + '.' + val.slice(-2);
// Append $
val = '$' + val;
textInput.value = val;
}
<input type="text" id="hello" />
Just to show an alternative starting point using Intl.NumberFormat.prototype.format(). Feel free to adjust to your requirements.
function formatAmount(el){
el.value = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', minimumIntegerDigits: 3 }).format(parseFloat(el.value.indexOf('$') === 0 ? el.value.substr(1) : el.value));
}
<input type="text" onblur="formatAmount(this);" />
My guess is that your function is being executed multiple times at the same time, the first execution is not even finished before the next one starts. You need to check if the function is already running.
I'm creating a simple binary to decimal converter page with an option to compare. My binary to decimal function works fine and jQuery can run and display it to the DOM. My compare function works fine in console but doesn't work when called on by a jQuery click function. Console.log works with the exact same numbers outside of the jQuery function, but not inside. Here's the jsfiddle: https://jsfiddle.net/deniswells59/ekdtk60t/
//simple compare function
var result = "";
var assert_equal = function(bin, dec) {
if(bin === dec){
return result = ("They are Equal!");
} else {
return result = ("They aren't Equal!");
};
};
//this works fine as well as .binaryToDecimal(), which I didn't include
$("#convert").click(function(){
var value = $("#binToConvert").val();
var valueConverted = value.binaryToDecimal();
$("#display").html("<span class='results'>"+value+"</span> converts to <span class='results'>"+valueConverted+"</span>");
});
//this ALWAYS displays "They aren't Equal!"; console.log says otherwise
$("#compare").click(function() {
var binary =$("#binary").val();
var decimal =$("#decimal").val();
binary = binary.binaryToDecimal();
assert_equal(binary, decimal);
$("#display").html("<span class='results'>"+result+"</span>");
});
You need to make sure they're the same type. Right now bin is a number and dec is a string (because jQuery's .val() always returns a string, even if the user entered a number). bin is a number because your binaryToDecimal function returns a number.
Just convert dec and bin to the same type before you compare them in your assert_equal function. Otherwise you can just use == if you do not care about type.
Something like this should do the trick:
var assert_equal = function(bin, dec) {
if(parseInt(bin) === parseInt(dec)){
return result = ("They are Equal!");
} else {
return result = ("They aren't Equal!");
};
};
You should add the function to the assert_equal as below
var assert_equal = function(bin, dec) {
if(bin.binaryToDecimal() == dec)
return result = ("They are Equal!");
}
I'm working on jquery.
i want to check the validation on todate and from date.
want to convert my string into double digit (need to add 0 if user enter single digit value)
how can i give double digit as user enter single digit value into textbox?
expected output is
var HourPerWeek = $("#Hour").val();
-- if user enter value 2 i need to convert it into 02
var MinPerWeek = $("#Min").val();
-- if user enter value 1 i need to convert it into 01
Instead of length of string ?
function returnDoubleDigits(str) {
return str.length === 1 ? '0' + str : str;
}
e.g.
var HourPerWeek = returnDoubleDigits($("#Hour").val());
Fiddle
Would this work,just check the string length and then add a zero if it is shorter than 2
var HourPerWeek;
if ($("#Hour").val().length < 2){
HourPerWeek = "0"+ $("#Hour").val();
}
else{
HourPerWeek = $("#Hour").val();
}
You will have to add the 0 to the beginning of the string manually like in this example:
String.prototype.paddingLeft = function (paddingValue) {
return String(paddingValue + this).slice(-paddingValue.length);
};
var HourPerWeek = $("#Hour").val().paddingLeft('00');
Explanation: You can call paddingLeft on any string. It will add the chars, that you pass as an argument to the left of the string and return a string with exactly the length of the given argument. More examples:
''.paddingLeft('00') // returns '00'
'1'.paddingLeft('00') // returns '01'
'11'.paddingLeft('00') // returns '11'
'111'.paddingLeft('00') // returns '11'
'1'.paddingLeft(' ') // returns ' 1'
Have this as a function which checks for length of passed parameter.
function returnTwoDigit(var Data){
if (Data.length != 2) {
if (Data.length == 1) {
Data= "0" + Data;
}
return Data
}
I have scenario where if user enters for example 000.03, I want to show the user it as .03 instead of 000.03. How can I do this with Javascript?
You can use a regular expression:
"000.03".replace(/^0+\./, ".");
Adjust it to your liking.
This actually is trickier than it first seems. Removing leading zero's is not something that is standard Javascript. I found this elegant solution online and edited it a bit.
function removeLeadingZeros(strNumber)
{
while (strNumber.substr(0,1) == '0' && strNumber.length>1)
{
strNumber = strNumber.substr(1);
}
return strNumber;
}
userInput = "000.03";
alert(removeLeadingZeros(userInput));
How about:
function showRounded(val) {
var zero = parseInt(val.split('.')[0],10) === 0;
return zero ? val.substring(val.indexOf('.')) : val.replace(/^0+/,'') );
}
console.log(showRounded('000.03')); //=> ".03"
console.log(showRounded('900.03')); //=> "900.03"
console.log(showRounded('009.03')); //=> "9.03"
Or adjust Álvaro G. Vicario's solution to get rid of leading zero's into:
String(parseFloat("090.03")).replace(/^0+\./, ".")
This function will take any string and try to parse it as a number, then format it the way you described:
function makePretty(userInput) {
var num,
str;
num = parseFloat(userInput); // e.g. 0.03
str = userInput.toString();
if (!isNaN(num) && str.substring(0, 1) === '0') {
str = str.substring(1); // e.g. .03
} else if (isNaN(num)) {
str = userInput; // it’s not a number, so just return the input
}
return str;
}
makePretty('000.03'); // '.03'
makePretty('020.03'); // '20.03'
It you feed it something it cannot parse as a number, it will just return it back.
Update: Oh, I see If the single leading zero needs to be removed as well. Updated the code.
Assuming your input's all the same format, and you want to display the .
user = "000.03";
user = user.substring(3);
You can convert a string into a number and back into a string to format it as "0.03":
var input = "000.03";
var output = (+input).toString(); // "0.03"
To get rid of any leading zeroes (e.g. ".03"), you can do:
var input = "000.03";
var output = input.substr(input.indexOf(".")); // ".03"
However, this improperly strips "20.30" to ".30". You can combine the first two methods to get around this:
var input = "000.03";
var output = Math.abs(+input) < 1 ?
input.substr(input.indexOf(".")) :
(+"000.03").toString();