Javascript value set null if value equals nothing - javascript

Right now I am working on a timesheet where users can set their in time, their out time, and how long they've been at lunch. Then I use a function that subtracts the in time & the lunch from their out time to figure out their hours, plus possible overtime. What I want is to have javascript set the value of the overtime field to '' (aka null) if the amount of time they were at work is 8 hours or less.
My code for checking overtime is this:
// Return difference between two times in hh:mm[am/pm] format as hh:mm
function checkOvertime(timein, timeout, away) {
// Small helper function to pad single digits
function z(n){return (n<10?'0':'') + n;}
// Get difference in minutes
var subtotal = daytimeStringToMins(timeout) - daytimeStringToMins(timein) - timeStringToMins(away);
var regularhours = '08:00';
if (subtotal > timeStringToMins(regularhours)) {var overtime = daytimeStringToMins(timeout) - daytimeStringToMins(timein) - timeStringToMins(away) - timeStringToMins(regularhours);}
else {var overtime = '0';}
return z(overtime/60 | 0) + ':' + z(overtime % 60);
}
and then in my calculation function I have this:
if (checkOvertime(timein, timeout, away).value == '00:00') {
document.getElementById("date-1-overtime").value = '';
} else {
document.getElementById("date-1-overtime").value = checkOvertime(timein, timeout, away);
}
So if a person is at work for 8 hours, then the "date-1-overtime" field says "00:00" but I would like it to put nothing in there so the sheet prints out more cleanly.
I think maybe I am confusing the difference between strings and integers in the calculation functions but I'm not sure, hopefully someone could help me!

I think you should change this method to use regular expressions to extract the appropriate parts of the input and then use parseint to get the value in a numeric form.
Convert that to minutes and if the minutes are less than or equal to 480 (8 * 60), return the actual string.
Also, you can't really assign a null value to an html param. null is not the same as 0. null is essentially, undefined.
You should return the number of minutes worked overtime from your function and use 0 for overtime if the user didn't work overtime.

Related

How to create number suffixes such as "100K" without having to be repetitive?

I've been having a problem that when my auto clicker in my clicker game goes fast enough to get to 200 thousand, it starts to lag, and then it doesn't function properly, or as fast.
Is there a way to make 100 thousand turn into 100K, and 101 thousand turn into 101K without being repetitive?
I tried this with my original code, and realized putting up to 1000 suffixes into each function would be a little too hard:
if (number >= 100000) {
document.getElementById(ID).innerHTML = "100K"
}
if (number >= 101000) {
document.getElementById(ID).innerHTML = "101K"
}
and on and on.
I don't want multiple if statements!
This would work, but it would take up way too much space, and I know there is an easier way to it, but I just couldn't find it. Can anyone provide a way to do this?
Try separating the job of formatting your number into a different function.
SUFFIXES = 'KMBTqQsSOND' // or whatever you'd like them to be
function getSuffixedNumber(num) {
var power = Math.floor(Math.log10(num));
var index = Math.floor(power / 3);
num = Math.round(num / Math.pow(10, (index * 3))); // first 3 digits of the number
return num + (SUFFIXES[index - 1] || ''); // default to no suffix if we get an out of bounds index
}
You can call the function like this: var x = getSuffixedNumber(101000), the value of x will be "101K".

JQuery not showing correct decimal output

My problem with this is, everything is fine up to two decimal places when its preceded 1-9, however if the number is a 10th, then my script will only show to one decimal place.
E.g 200.19, 5000.42, 12.98 << will be fine however if the output should be 123.10 it will display 123.1
Here's my code:
jQuery(document).ready(function() {
function ReplaceNumberWithCommas(yourNumber) {
//Seperates the components of the number
var n= yourNumber.toString().split(".");
//Comma-fies the first part
n[0] = n[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
//Combines the two sections
return n.join(".");
}
function loanCalc() {
//Get the parameter from the form
var rate=jQuery('#start_rate').val();
var priceValue=jQuery('#input_1_2').val();
console.log("price value before"+priceValue);
if(priceValue.indexOf('£') == 0) {
var strEnd=jQuery('#input_1_2').val().indexOf(',') - 1;
priceValue=parseInt(priceValue.substr(1,priceValue.strEnd))*1000;
}else{
priceValue=priceValue;
}
var princ = parseInt(priceValue);
var term = parseInt(jQuery('#input_1_3').val());
var intr = rate / 1200;
console.log("price"+priceValue+" term"+term+" rate"+rate);
var calculation = princ * intr / (1 - (Math.pow(1/(1 + intr), term)));
console.log("paymenet"+calculation);
var rePayment= calculation*term;
var costOfCredit=princ-rePayment;
//set the value
jQuery('#figure').html('£'+ ReplaceNumberWithCommas(calculation.toFixed(2)));
jQuery('#rate').html(rate+"%");
jQuery('#total').html('£' +
ReplaceNumberWithCommas(rePayment.toFixed(2)));
jQuery('#credit').html('£' + ReplaceNumberWithCommas(
Math.abs(costOfCredit.toFixed(2 ))));
As you can probably guess, there are 3 fields that I am displaying, the calculation, which is a percentage, 'rePayment' and 'costOfCredit'. The weird thing is 'rePayment' works fine and has no problem showing the 2nd decimal place even if its a 10th/ends with zero.
So my question is can you guys help me find what my problem is with getting the 2nd decimal place to show is?
When you call Math.abs(), it's converting the string with 2 digits after the decimal back to a number, which loses the trailing zeroes. You should call Math.abs() first, then call toFixed() on this to add the trailing zeroes.
jQuery('#credit').html('£' +
ReplaceNumberWithCommas(Math.abs(costOfCredit).toFixed(2)));

Why is this not a clear integer type and how to make it clear?

I have this code:
wallboard.data.Timer = function () {
$("div[data-value]").each(function () {
var time = $(this).attr("data-value");
if (time > 0) {
time += 1000;
$(this).attr("data-value", time).text(TimeToText(time));
}
});
}
The function TimeToText() simply takes a millisecond value and output it as hour:seconds (00:00).
The attribute data-value contains a millisecond value and is stores in the variable time.
This is my "debug" output:
var time = $(this).attr("data-value"); time = 4376
if (time > 0) { is true as 4376 is larger than 0
time += 1000; after this "time" is 43761000 - her it starts concatenating the text "4376" and "1000" and this is the proof that the JavaScript engine thinks time is a string type.
How do I make it clear that time should be an integer type?
var time = $(this).attr("data-value");
var timeInt = parseInt(time) + 1000;
You can use coercion trough the unary +, or just wrap it in a parseInt with a base of 10.
wallboard.data.Timer = function () {
$("div[data-value]").each(function () {
var time = parseInt($(this).attr("data-value"), 10);
if (time > 0) {
time += 1000;
$(this).attr("data-value", time).text(TimeToText(time));
}
});
}
Also, you could have searched for "javascript string to number" and you would find billions of results.
EDIT: Why not interpret numeric strings as numbers automatically? Because that would be a very unpleasant deviation from the convention: in JS you try to modify as little as possible your outputs. If you then wanted to actually concatenate two numeric strings together, you'd have to do lots of hacks to do it:
Instead of var a = "1000" + "10" to get "100010", you would have to do something like this
var a = ["1000", "zz10"].join(""); // note the "zz", so it's not plain numeric.
a = a.replace("zz", ""); // replace "zz" with nothing.
// now `a` would be "100010"
You need to convert the string retrieved with attr() into a number, e.g.
var time = +($(this).attr("data-value"));
You can use unary plus operator to convert the string attribute value to a number(you can also use parseInt())
var time = +$(this).attr("data-value");
You should convert the string to integer before adding it with 1000.
var time = parseInt($(this).attr("data-value"));

Change count down to count up

This script counts down from 60 to 0 and stops when it reaches 0.
<script type="text/javascript">
var counttx= "60";
var counterrx=setInterval(timerrx, 1000); //1000 will run it every 1 second
function timerrx()
{
counttx=counttx-1;
if (counttx < 0)
{
clearInterval(counterrx);
return;
}
document.getElementById("timerrx").innerHTML=counttx; // watch for spelling
}
</script>
Instead of counting down, I want the script to count up. I changed the - to a + in counttx=counttx-1; but then the following happend:
60
601
6011
60111
etc.
Looks like counttx is a string, and javascript is appending '1'. Try:
counttx = +counttx + 1;
Edit: or just remove the quotes in the var statement:
var counttx = 60;
If one operand of - operator is string and another is number JS converts the string to number. Thats why count down is working even if counttx is string. But when one operand of + is string and another is number JS converts the number to string and does a string concatenation. Thus you are getting 601, 6011 etc. instead of count up. To fix this you can declare counttx as integer.
var counttx = 60;
Remove the quotes from var countxx="60";
Write it as
var countxx=60;
and then change it to
counttx=counttx+1;
When you mention the value within quotes, it considers it as string and just appends 1 to the value, that is the reason your getting 601, 6011 etc.
You need to parse var to integer first then increment it. Use counttx = parseInt(counttx) + 1;
Do you want to count from 0 to 60? If so swap the 60 and the 0 in your script and change this line counttx = counttx + 1; to counttx = counttx - 1. Also get rid of the double quotes around 60.

Adding leading zeros to a Javascript timer

I'm attempted to add leading zeros to the seconds value and I keep running into errors. I've tried a number of selected solutions posted here and can't seem to make it work.
I'm pulling values from the spans because those values are coming from the database.
var timer = $('.timer');
$('.prev-button,.next-button').hide();
setInterval(function () {
var m = $('.min', timer),
s = $('.sec', timer);
if (m.length == 0 && parseInt(s.html()) <= 0) {
timer.html('Proceed to the Next Slide');
$('.prev-button,.next-button').fadeIn();
}
if (parseInt(s.html()) <= 0) {
m.html(parseInt(m.html() - 1));
s.html(60);
}
if (parseInt(s.html()) < 10) {
$('.sec').prepend(0)
}
if (parseInt(m.html()) <= 0) {
timer.html('Time remaining for this slide - <span class="sec">59</span> seconds')
}
s.html(parseInt(s.html() -1));
}, 1000);
http://jsfiddle.net/certainstrings/a2uJ2/1/
I've modified your Fiddle to make it work. http://jsfiddle.net/a2uJ2/3/
You should store the time in javascript int vars instead of reading it from the html elements every time. This causes maintainability problem as you are attaching logic to the layout of your html document.
I haven't fixed all your code but i've created two variables that are used to perform the calculations instead.
Couple of things: You'd be better off registering a start time, and comparing against that inside the interval function. Timers are not guaranteed to be precise, but will instead trigger on or after the interval you specify. If the computer's busy, the timer might be late.
Also, if you're using parseInt, always, always specify a radix argument (the number base). If you don't, the string "08" will will be parsed to "0" because a leading zero is intepreted as an octal (base-8). So use parseInt(string, 10) to parse to a normal base-10 number.
As for adding the leading zero, I'd say you should keep a couple variable for total amount of seconds, rather than reading/writing to the elements all the time.
Updated you jsfiddle
var duration, startTime, interval;
duration = parseInt($(".min").text(), 10) * 60 + parseInt($(".sec").text(), 10);
startTime = (new Date()).getTime();
function countDown() {
var elapsed, remaining, m, s;
elapsed = ((new Date()).getTime() - startTime) / 1000;
remaining = duration - elapsed;
if(remaining <= 0) {
clearInterval(interval);
$(".timer").text('Proceed to the Next Slide');
$('.prev-button,.next-button').fadeIn();
} else {
m = String(Math.round(remaining / 60));
s = String(Math.round(remaining % 60));
if( s < 10 ) {
s = "0" + s;
}
$(".min").text(m);
$(".sec").text(s);
}
}
interval = setInterval(countDown, 500);
This is just a minimal change from you code. I'd probably do something fundamentally different to keep the markup and JS as separate as possible, and so on and so forth, but this works too.
try it like this:
if (parseInt(s.html()) < 10) {
$('.sec').val('0' + $('.sec').val());
}
You're going to need to treat the value as a string rather than as an int. JavaScript is pretty aggressive about converting things that look like numbers into numbers, and that's what's happening here.

Categories

Resources