Passed Variable not working with my function - Javascript - javascript

I've got text entry box and a countdown on the same page. I want to take the time from the box and enter it into the counter. I've got a variable back from the text box "setTime". I wanted to put that directly into my timeSplit function (to convert the time into seconds) but when I do I get an error that "time.split is not a function". What am I doing wrong here?
When I have a static variable enter the function (e.g. time = "12:12:12") everything works perfectly. - except its not using the right time
When I run the pop up alert on setTime before the timeSplit function I see my time like this "12:12:12" so its coming from the counter without a problem and I don't get a NaN error
Why would a time variable work when its static but not when its passed
I tried converting the setTime to a string but that just lead to NaN errors even when I tried to convert the sec variable back to an int.
I think this is the relevant code let me know if you need more.
var setTime = 0;
var $fromTime = $("#formEntry");
$("#setTime").off("click").on("click", function(){
setTime = $fromTime.val();
});
function timeSplit(){
//time = "12:12:12";
tt = time.split(":");
sec = tt[0]*3600+tt[1]*60+tt[2]*1;
return sec;
}
var time = setTime;
//var time = "12:12:12";
var sec = timeSplit(time);

Your function timeSplit() does not take any arguments. It needs to be timeSplit(time) so that JavaScript knows you are talking about calling the method .split() on an object called time rather than a function just called time.split().
If this wasn't just a typo (I've done that before), I suggest you read up some on function arguments and parameters so you know you understand how this works, it's really important.

Related

Javascript: Storing the current time's timestamp value

Is there a way to store the current timestamp in a Javascript variable? The reason is I want to compare Javascript's current time value with a Django time variable, and whenever the time matches, it will send a popup notification.
I guess reloading the page maybe every 3 seconds or so would work, but that seems extremely inefficient.
I'm not sure exactly what you're trying to do here. It's not likely the times will ever match exactly unless you check every millisecond, but you can always check when the time is greater than the django variable, or within a certain range. This will check the time every three seconds.
var django = // Create a javascript date object from django timestamp here
var interval = setInterval(function(){checkTime()}, 3000);
function checkTime() {
var d = new Date();
if (d >= django) {
//Do something here
clearInterval(interval);
}
}

How to write a generic function that passes one argument to then function then called multiple times

I have been stuck on this homework:
Create a generic function that outputs one line of the countdown on
the web page, followed by an alert, and receives the data to output as
an input parameter.
Use that function to output each line of the countdown, and an alert.
Please note that you are outputting the countdown to the browser
window this time, not to an alert!
The alert is only being used to signal when to output the next line
I need help in how to come up with a generic function that passes only one argument and then can be called 13 times. To write a for loop that output the numeric part of a countdown.
I think the key here is that they're asking for "Generic".
That means one function that doesn't have to know anything but what it's doing.
It also usually means that it shouldn't remember anything about what it did last time, or what it's going to do next time it's called (unless you're writing a generic structure specifically for remembering).
Now, the wording of the specification is poor, but a generic function which:
takes (input) data to write
writes the input to the page
calls an alert
is much simpler than you might think.
var writeInputAndAlert = function (input) {
// never, ever, ***ever*** use .write / .writeLn in the real world
document.writeLn(input);
window.alert("next");
};
If I was your teacher, I would then rewrite window.alert to handle the non-generic portion.
It's non-generic, because it knows the rules of the program, and it remembers where you are, and where you're going.
var countFrom = 100,
currentCount = countFrom,
countTo = 0;
var nextCount = function () {
currentCount -= 1;
if (currentCount >= countTo) { writeInputAndAlert(currentCount); }
};
window.alert = nextCount;
edit
var countdownArray = ["ten", "nine", "eight", "Ignition Start", "Lift Off", "We have Lift Off"],
i = 0, end = countdownArray.length, text = "",
printAndAlert = function (item) {
alert();
document.write(item);
};
for (; i < end; i += 1) {
text = countdownArray[i];
printAndAlert(text);
}
This really doesn't need to be any harder than that.
printAndAlert is a generic function that takes one input, writes that input and triggers an alert.
You call it inside of a for loop, with each value in your array.
That's all there is to it.
If I understand correctly, you want to create a function that will allow you to pass the data once, and then you can call that function to output the data line by line.
To do this exactly that way isn't possible, but this method is almost the same:
function createOutputFunction(dataArray)
{
return function() {
document.write(dataArray.shift()); // This writes the first element of the dataArray to the browser
};
}
//It can then be used like this
outputFunction = createOutputFunction(["Banana", "Mango", "Apple"]);
outputFunction();
outputFunction();
outputFunction();
The "createOutputFunction" function returns a function that can read the "dataArray" variable and print its first element every time it is called.

Find the lapse of time

I'm trying to get the time lapse between 2 diferent hours....
function time()
{
var startime=(document.getElementById("horaentrada").value);
var endtime=(document.getElementById("horasaida").value);
document.getElementById("total_horas").value = (endtime-startime);
}
the idea is to fill a html input "total_horas" with the result. The function is triggered by an onchange event. The entry format is "HH:mm:ss", by instance 9:35:22.
I've tried a lot of things, but, no one works I get NaN.
Try this:
function time()
{
var startime=(document.getElementById("horaentrada").value);
var endtime=(document.getElementById("horasaida").value);
document.getElementById("total_horas").value= (parseFloat(endtime,10)-parseFloat(startime, 10));
}
Also, make sure to run the function after the dom is loaded.
Fiddle: http://jsfiddle.net/LnLdB/2/ . Just be gentle with the stuff you input in the boxes.
EDIT: Here is an updated fiddle, using moment.js. It subtracts hours in the format "HH:mm:ss": http://jsfiddle.net/LnLdB/13/

JavaScript calculate difference between two dates, display number in text input

I have been working for some time on an application form for an insurance company. They sell travel insurance.
As an additional small feature they have asked me to take the dates the depart and return dates the user inputs, calculate the number of days between them and then display number in the 'days' box. The goal of which is so that the user can enter the two dates and have the number of days auto-calculated.
I have already created a function which properly calculates the date and I have tested it using manually assigned date values.
My issue has come up when using the JS calendar.
What I tried to do was use the onblur of the second box to access the function and spit the date out into the 'days' box. I quickly realized that the onblur is triggered before the code for the JS calendar puts in the date, hence there is no date for the function and the function does not run.
I then tried to use onchange and realized it would not work either because the user is not actually changing the date, code is.
So what I tried to do next was use an Interval to trigger the function, this is where I have run into issues.
Below is my code in my caldate.js file which is attached to my HTML form.
var namestart = new Array ();
namestart[0] = "trav_emer_single_date_go";
namestart[1] = "trav_emer_extend_date_go";
namestart[2] = "allinc_single_date_go";
namestart[3] = "allinc_annual_date_go";
namestart[4] = "cancel_date_go";
namestart[5] = "visitor_supervisa_date_go";
namestart[6] = "visitor_student_date_go";
namestart[7] = "visitor_xpat_date_go";
var namend = new Array ();
namend[0] = "trav_emer_single_date_ba";
namend[1] = "trav_emer_extend_date_ba";
namend[2] = "allinc_single_date_ba";
namend[3] = "allinc_annual_date_ba";
namend[4] = "cancel_date_ba";
namend[5] = "visitor_supervisa_date_ba";
namend[6] = "visitor_student_date_ba";
namend[7] = "visitor_xpat_date_ba";
var names = new Array ();
names[0] = "trav_emer_single_days";
names[1] = "trav_emer_extend_days";
names[2] = "allinc_single_days";
names[3] = "allinc_annual_days";
names[4] = "cancel_days";
names[5] = "visitor_supervisa_days";
names[6] = "visitor_student_days";
names[7] = "visitor_xpat_days";
function daysBetween() {
for (var i = 0; i < 8; i++) {
//Get the value of the current form elements
var start = document.getElementById(namestart[i]).value;
var end = document.getElementById(namend[i]).value;
//Duration of a day
var d = 1000*60*60*24;
// Split Date one
var x = start.split("-");
// Split Date two
var y = end.split("-");
/// // Set Date one object
var d1 = new Date(x[0],(x[1]-1),x[2]);
// // Set Date two object
var d2 = new Date(y[0],(y[1]-1),y[2]);
//
// //Calculate difference
diff = Math.ceil((d2.getTime()-d1.getTime())/(d));
//Show difference
document.getElementById(names[i]).value = diff;
}
}
function interval() {
var int = setInterval(function(){daysBetween()},500);
}
The list of arrays at the beginning is the names of the elements which I need to access. What I intend to do with my function is on each interval run through a loop which checks all 8 of these elements. namestart[] and namend[] are the start and end dates entered by the user. names[] lists the names of the boxes where days are to be displayed.
I have not been able to even test the interval portion because I can't even get the daysBetween() to run once with manually assigned value="date" for testing purposes, it just won't run at all.
The issue is quite simple really: document.getElementById(namestart[i]).value isn't pullig out a value, it just hangs the script because it can't find the value. I have also tried using the form_name.elements().value notation and the form_name.element_name.value notation to no avail.
I am really stumped here as far as I can tell the code should be working, I give a list of the names of the items and I tell the script to access them using - what I have used, and seen many times to work getElementByID.
Any assistance would be greatly appreciated as I am not quite sure where to go from here.
As requested here is a JS fiddle link: http://jsfiddle.net/L2H9N/ - pure JS no libraries.
What I think is happening is your daysBetween function is executing before the DOM is ready, which is throwing an error and nuking the rest of your javascript. To fix it, you'll need to put the call to daysBetween into a callback for window.onload or attach it to a callback in your calender.
It would also be a good idea to coalesce your nulls or at least check for them before proceeding to do calculations on the variables.

Javascript Split method not working as expected

I have a method in javascript that use the split method to store the time in an array and then convert the time to seconds. But when I debug, the array always has first 2 elements and ignore the last one. Not sure why?
GetSeconds : function (time) {
var timesecs = 0;
var min = 1;
var timeArray = time.split(ctx.options.separator); //this always contain 2 elements
while (timeArray.length > 0) {
timesecs += min * parseInt(timeArray.pop());
min *= 60;
}
return timesecs;
}
ctx.options.separator is a variable that stores my delimiter. I was trying with ":" and time passed was "00:00:00". This method is called from another method which increments the second.
I tried it in IE, Chrome and Firebug. This behaves differently when I debug through Visual Studio (as this code is in my .net app)
I tried a fiddle and everything works fine there. Are you sure, that ctx.options.separator works as expected?
The problem may be a browser issue if ctx.options.separator is being generated properly.
Which browser are you using?
Use this cross browser method that will make everything work as expected no matter which browser you use.
http://blog.stevenlevithan.com/archives/cross-browser-split
It always has worked for me.

Categories

Resources