multiple alarm clock in javascript using dynamic generated input elements in javascript - javascript

I am trying to make a web page which will allow to set multiple alarms using dynamic element creation property of javascript but I'm not able to get the values of these multiple elements and create a alert on that time.
This is my code so far
<div id="TextBoxContainer">
<!--Textboxes will be added here -->
</div>
<br />
<input id="btnAdd" type="button" value="add" onclick="AddTextBox();" />
<script type="text/javascript">
var room = 0;
var i = 0;
function GetDynamicTextBox(){
return '<div>Alarm ' + room +':</div><input type="number"style="text-align:center;margin:auto;padding:0px;width:200px;" min="0" max="23" placeholder="hour" id="a'+room+'" /><input type="number" min="0" max="59" placeholder="minute" style="text-align:center; padding:0px; margin:auto; width:200px;" id="b'+room+'" /><input type="date" style="margin:auto;text-align:center; width:200px; padding:10px"><input type="button" value ="Set" onclick = "AddAlarm('+room+');" /> <input type="button" value ="Remove" onclick = "RemoveTextBox(this)" />';
}
function AddTextBox() {
var div = document.createElement('DIV');
div.innerHTML = GetDynamicTextBox("");
document.getElementById("TextBoxContainer").appendChild(div);
}
function RemoveTextBox(div) {
document.getElementById("TextBoxContainer").removeChild(div.parentNode);
}
function RecreateDynamicTextboxes() {
var html = "";
html += "<div>" + GetDynamicTextBox() + "</div>";
document.getElementById("TextBoxContainer").innerHTML = html;
room++;
}
window.onload = RecreateDynamicTextboxes;
function AddAlarm(values){
var hour = document.getElementById('');
var minute = document.getElementById('');
var date = document.getElementById('');
}
</script>

To create a notification whenever a given time or state is reached, I think you are looking for setInterval (see reference).
This method allows you to take action at a regular interval and it tries to honor that interval the best it can. It opens to a common mistake if your action can take longer than that interval duration so be careful not using a too short interval. In such case, actions can overlap and weird behavior will occur. You do not want that to happen so don't be too greedy when using that.
For an alarm project, I would recommend an interval of one second.
Example (not tested):
JavaScript
var alarmDate = new Date();
alarmDate.setHours(7);
alarmDate.setMinutes(15);
// set day, month, year, etc.
var ONE_SECOND = 1000; // miliseconds
var alarmClock = setInterval(function() {
var currentDate = new Date();
if (currentDate.getHours() == alarmDate.getHours() &&
currentDate.getMinutes() == alarmDate.getMinutes()
/* compare other fields at your convenience */ ) {
alert('Alarm triggered at ' + currentDate);
// better use something better than alert for that?
}, ONE_SECOND);
To add dynamic alarms, you could put them into an array then have your setInterval iterate over it.
In the long run you will probably get sick of alert and feel the need to use something that doesn't break the flow of your application. There are a lot of possibilities, one being the use of lightboxes that could stack over each other. That way you would be able to miss an alarm and still be notified by the next one.
Hope this helps and good luck!

You forgot the ID attribute on the date input and you were collecting the input elements in AddAlarm instead of their values.
EDIT: To check the alarms you have to store them and check every minute, if the current date matches one of the alarms. I added a short implementation there.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="TextBoxContainer">
<!--Textboxes will be added here -->
</div>
<br />
<input id="btnAdd" type="button" value="add" onclick="AddTextBox();" />
<script type="text/javascript">
var alarms = {};
var room = 0;
var i = 0;
setInterval(function() {
var current = new Date();
for (var nr in alarms) {
var alarm = alarms[nr];
console.log("checking alarm " + nr + " (" + alarm + ")");
if(current.getHours() == alarm.getHours()
&& current.getMinutes() == alarm.getMinutes()) { // also check for day, month and year
alert("ALERT\n"+alarm);
} else{
console.log('Alarm ' + nr + '('+alarm+') not matching current date ' + current);
}
}
}, 60000);
function GetDynamicTextBox(){
return '<div>Alarm ' + room +':</div><input type="number"style="text-align:center;margin:auto;padding:0px;width:200px;" min="0" max="23" placeholder="hour" id="a'+room+'" /><input type="number" min="0" max="59" placeholder="minute" style="text-align:center; padding:0px; margin:auto; width:200px;" id="b'+room+'" /><input type="date" style="margin:auto;text-align:center; width:200px; padding:10px" id="c'+room+'"><input type="button" value ="Set" onclick = "AddAlarm('+room+');" /> <input type="button" value ="Remove" onclick = "RemoveTextBox(this)" />';
}
function AddTextBox() {
var div = document.createElement('DIV');
div.innerHTML = GetDynamicTextBox("");
document.getElementById("TextBoxContainer").appendChild(div);
}
function RemoveTextBox(div) {
document.getElementById("TextBoxContainer").removeChild(div.parentNode);
}
function RecreateDynamicTextboxes() {
var html = "";
html += "<div>" + GetDynamicTextBox() + "</div>";
document.getElementById("TextBoxContainer").innerHTML = html;
room++;
}
window.onload = RecreateDynamicTextboxes;
function AddAlarm(values){
var hour = $('#a'+values).val();
var minute = $('#b'+values).val();
var date = $('#c'+values).val();
console.log(hour + ':' + minute + ' on ' + date);
var dateObj = new Date(date);
dateObj.setMinutes(minute);
dateObj.setHours(hour);
console.log(dateObj);
alarms[values] = dateObj;
}
</script>

So far I'm able to generate a alert when the values match the system time but I don't know how to delete the array value when an element is deleted. I am not able to do it. This is my code so far:
<script type="text/javascript">
var snd = new Audio("clock.mp3"); // buffers automatically when created
// Get
if (localStorage.getItem("test")) {
data = JSON.parse(localStorage.getItem("test"));
} else {
// No data, start with an empty array
data = [];
}
var today = new Date();
var d = today.getDay();
var h = today.getHours();
var m = today.getMinutes();
//since page reloads then we will just check it first for the data
function check() {
//current system values
console.log("inside check");
//if time found in the array the create a alert and delete that array object
for(var i = 0; i < data.length; i++) {
var today = new Date();
var d = today.getDay();
var h = today.getHours();
var m = today.getMinutes();
if (data[i].hours == h && data[i].minutes == m && data[i].dates == d ) {
data.splice(i,1);
localStorage["test"] = JSON.stringify(data);
snd.play();
alert("Wake Up Man ! Alarm is over ");
}
}
if((data.length)>0)
{
setTimeout(check, 1000);
}
}
//we do not want to run the loop everytime so we will use day to check
for(var i =0 ; i< data.length; i++)
{
if((data[i].dates == d) && (data[i].hours >= h) && (data[i].minutes >= m) )
{
check();
}
}
console.log(data);
var room = 1;
//var data = [];
var i = 0;
function GetDynamicTextBox(){
var date = new Date();
var h = date.getHours();
var m = date.getMinutes();
var d = date.getDay();
return '<div>Alarm ' + room +':</div><input type="number" style="text-align:center;margin:auto;padding:0px;width:200px;" min="0" max="23" value ='+h+' placeholder="hour" id="a'+room+'" /> <input type="number" min="0" max="59" placeholder="minute" style="text-align:center; padding:0px; margin:auto; width:200px;" id="b'+room+'" value ='+m+' /> <select id="c'+room+'" style="margin:auto; width:150px; padding:10px; color: black" required> <option value="1">Monday</option> <option value="2">Tuesday</option> <option value="3">Wednesday</option> <option value="4">Thursday</option> <option value="5">Friday</option> <option value="6">Saturday</option> <option value="0">Sunday</option> </select> <input type="button" value ="Set" onclick = "AddAlarm('+room+');" /> <input type="button" value ="Remove" onclick = "RemoveTextBox(this)" />';
}
function AddTextBox() {
room++;
var div = document.createElement('DIV');
div.innerHTML = GetDynamicTextBox("");
document.getElementById("TextBoxContainer").appendChild(div);
}
function RemoveTextBox(div) {
document.getElementById("TextBoxContainer").removeChild(div.parentNode);
}
function RecreateDynamicTextboxes() {
var html = "";
html += "<div>" + GetDynamicTextBox() + "</div>";
document.getElementById("TextBoxContainer").innerHTML = html;
}
window.onload = RecreateDynamicTextboxes;
function AddAlarm(values){
var hour = $('#a'+values).val();
var minute = $('#b'+values).val();
var date = $('#c'+values).val();
//get the current time and date
var today = new Date();
//current system values
var d = today.getDay();
var h = today.getHours();
var m = today.getMinutes();
//first check that whether a same date present in the array or not then push it
var found = -1;
for(var i = 0; i < data.length; i++) {
if (data[i].hours == hour && data[i].minutes == minute && data[i].dates == date ) {
found = 0;
break;
}
}
//if value does not present then push it into the array
if(found == -1)
{
data.push({hours: hour, minutes: minute, dates: date});
//storing it into localstorage
localStorage.setItem("test", JSON.stringify(data));
}
else
{
alert("Same value Exists");
}
//console.log(data);
function check() {
//current system values
//console.log("inside check");
//if time found in the array the create a alert and delete that array object
for(var i = 0; i < data.length; i++) {
var today = new Date();
var d = today.getDay();
var h = today.getHours();
var m = today.getMinutes();
if (data[i].hours == h && data[i].minutes == m && data[i].dates == d ) {
data.splice(i,1);
snd.play();
alert("Wake Up Man ! Alarm is over ");
}
}
if((data.length)>0)
{
setTimeout(check, 1000);
}
}
//we do not want to run the loop everytime so we will use day to check
for(var i =0 ; i< data.length; i++)
{
if((data[i].dates == d) && (data[i].hours >= h) && (data[i].minutes >= m))
{
check();
}
}
}
</script>

Related

Chrome Extension: calculate in miliseconds and click button after specific seconds

Well i am practising on Chrome Extension , i'm newbie on this.
Here is my code.
popup.html
<!doctype html>
<html>
<head>
<title>Laser Script</title>
<script type="text/javascript" src="popup.js"></script>
<style type="text/css">
h1 { font-size: 22px; }
.powered {
font-size: 14px;
margin-top: 8px;
}
</style>
</head>
<body>
<h1>Scheduled Click</h1>
<div id="contentWrapper">
<input type="text" id="duration" placeholder="Duration">
<input type="text" id="attack_date" placeholder="Day/Month/Year">
<input type="text" id="attack_time" placeholder="00:00:00">
<button id="schedule">Start Attack</button>
</div>
<div class="powered">Courtesy of <img src="justpark_logo.png" width="170px"></div>
</body>
</html>
popup.js
function initialise () {
// here im calculating the remind time in (mileseconds) that the button have to be pressed
var attack_timeInput = document.getElementById("attack_time");
var attack_timeParts = attack_timeInput.value.split(":");
var hours = parseInt(attack_timeParts[0],10);
var minutes = parseInt(attack_timeParts[1],10);
var seconds = parseInt(attack_timeParts[2],10);
var mileseconds = parseInt(attack_timeParts[3],10);
var attack_DateInput = document.getElementById("attack_date");
var attack_DateInputParts = attack_DateInput.value.split("/");
var day = parseInt(attack_DateInputParts[0],10);
var month = parseInt(attack_DateInputParts[1],10);
var year = parseInt(attack_DateInputParts[2],10);
var durationInput = document.getElementById("duration");
var durationParts = durationInput.value.split(":");
var hours2 = parseInt(durationParts[0],10)*3600000;
var minutes2 = parseInt(durationParts[1],10)*60000;
var seconds2 = parseInt(durationParts[2],10)*1000;
var duration_mile = hours2+minutes2+seconds2;
var now = new Date();
var new_now = now.getTime();
var full_attack_date = new Date(year, month-1, day, hours, minutes, seconds, mileseconds);
var new_full_attack_date = full_attack_date.getTime();
var delayInputValue = new_full_attack_date - new_now - duration_mile;
function scheduleClick () {
document.getElementById("contentWrapper").innerHTML = 'The attack will start in ' + delayInputValue + 'miliseconds';
var codeString = 'var button = document.getElementById("troop_confirm_go"); setTimeout( function() { button.click(); },' + delayInputValue + ' )';
console.log(codeString);
chrome.tabs.executeScript({ code: 'console.log(document.getElementById("The attack will start ' + delayInputValue + ' miliseconds"))' });
chrome.tabs.executeScript({ code: codeString});
};
scheduleButton = document.getElementById("schedule");
scheduleButton.addEventListener('click', scheduleClick, true);
};
document.addEventListener('DOMContentLoaded', initialise, false);
So i have 3 inputs. I calculate the remind time until the button will be clicked. (it works)
But in this part
document.getElementById("contentWrapper").innerHTML = 'The attack will start in ' + delayInputValue + 'miliseconds';
it diplays
The attack will start in NaN miliseconds.
and the button is pressed instantly.
I ckeched also this code:
var p = 1 ; //it's outside the function as the var delayInputValue
document.getElementById("contentWrapper").innerHTML = 'The attack will start in ' + delayInputValue + 'seconds';
and it displays :
The attack will start in 1 miliseconds.
So here is my question, why it can't read and work with the var delayInputValue but i can the var p?
Can i fix it somehow ?
Got it - the initialise() function is called when your DOM content is finished loading. At that point, the user has not entered information into the text fields, so they show as null or undefined. When the code starts running with this data it produces data as NaN since the calculations don't work.
In order for the code to run properly, you need to place the code dealing with data from those fields inside the scheduleClick() function, like so:
function initialise () {
function scheduleClick () {
var attack_timeInput = document.getElementById("attack_time");
var attack_timeParts = attack_timeInput.value.split(":");
var hours = parseInt(attack_timeParts[0],10);
var minutes = parseInt(attack_timeParts[1],10);
var seconds = parseInt(attack_timeParts[2],10);
//var mileseconds = parseInt(attack_timeParts[3],10);
var attack_DateInput = document.getElementById("attack_date");
var attack_DateInputParts = attack_DateInput.value.split("/");
var day = parseInt(attack_DateInputParts[0],10);
var month = parseInt(attack_DateInputParts[1],10);
var year = parseInt(attack_DateInputParts[2],10);
var durationInput = document.getElementById("duration");
var durationParts = durationInput.value.split(":");
var hours2 = parseInt(durationParts[0],10)*3600000;
var minutes2 = parseInt(durationParts[1],10)*60000;
var seconds2 = parseInt(durationParts[2],10)*1000;
var duration_mile = hours2+minutes2+seconds2;
var now = new Date();
var new_now = now.getTime();
var full_attack_date = new Date(year, month-1, day, hours, minutes, seconds);
var new_full_attack_date = full_attack_date.getTime();
var delayInputValue = new_full_attack_date - new_now - duration_mile;
document.getElementsByTagName("div")[0].innerHTML = 'The attack will start in ' + delayInputValue + 'miliseconds';
};
scheduleButton = document.getElementById("schedule");
scheduleButton.addEventListener('click', scheduleClick, true);
};
document.addEventListener('DOMContentLoaded', initialise, false);
Note that I also removed the miliseconds variable as the inputs I was using included hours, minutes and seconds only. You should also add some code to sanitise inputs to make sure they are in the format you want before calling the function.
Hope that helps

return to zero after reach max value and add the remaining value javascript

sorry i am newbie here
i need some help,
this case like notice a time.
when real time passes input value, then span with id alertLabel will change.
the problem is, if input value plus with input with id Duration will exceed real minutes or hours.
this is my code example.
javascript.js
var alertLabel = document.getElementById("alertLabel");
var less = document.getElementById("lessThan").value.replace(":", "");
var late = document.getElementById("timeIn").value.replace(":", "");
var duration = parseInt(document.getElementById("Duration").value);
var outs = document.getElementById("timesOut").value.replace(":", "");
var lessInt = parseInt(less);
var lateInt = parseInt(late);
var outsInt = parseInt(outs);
var durationOut = outsInt + duration; // this will be exceed
var durationIn = lateInt + duration; // this will be exceed
function getAlert() {
let times = new Date();
let sh = times.getHours() + "";
let sm = times.getMinutes() + "";
let ss = times.getSeconds() + "";
let shLong = sh.length == 1 ? "0" + sh : sh;
let smLong = sm.length == 1 ? "0" + sm : sm;
let ssLong = ss.length == 1 ? "0" + ss : ss;
let shSm = shLong + smLong;
document.getElementById("clock").innerHTML = shLong + ":" + smLong + ":" + ssLong;
if (shSm >= outsInt && shSm < durationOut) {
alertLabel.innerHTML = "OUT!!";
} else if (shSm >= lessInt && shSm < lateInt) {
alertLabel.innerHTML = "hurry up, don't be late!!";
} else if (shSm >= lateInt && shSm < durationIn) {
alertLabel.innerHTML = "LATE!!";
} else {
if (shLong >= 21 || shLong <= 4) {
alertLabel.innerHTML = "good dream tonight !!";
} else if (shLong >= 5 && shLong <= 11) {
alertLabel.innerHTML = "spirit Morning !!";
} else if (shLong >= 12 && shLong <= 17) {
alertLabel.innerHTML = "happy Noon !!";
} else if (shLong >= 18 && shLong <= 20) {
alertLabel.innerHTML = "nice evening !!";
}
}
}
<!doctype html>
<html>
<head>
<title></title>
</head>
<body onload="getAlert();setInterval('getAlert()',1000)">
<span id="clock"></span>
<span id="alertLabel"></span>
<div></div>
<input class="" type="text" id="lessThan" value="13:45" name="lessThan"> <!-- when time to in is near -->
<input class="" type="text" id="timeIn" value="13:48" name="timeIn"> <!-- time in and get alert Late -->
<input type="text" id="timesOut" value="13:55" name="timesOut"> <!-- value time to out and get alert Out -->
<input type="text" name="Duration" id="Duration" value="5"> <!-- duration alert for id timeIn and timesOut if more than 100 is the problem, this input as minute -->
</body>
</html>
this is my last try, example in input id timeIn
var a = document.getElementById("timeIn").value.split(":");
for (var i = 0; i < duration; i++){
var b = parseInt(a[0]); // this for hours
var c = parseInt(a[1]); // this for minutes
var x = c + i;
if (x >= 60){
var n = b + 1;
x = x-60;
}
console.log(x);
}
in my last try, in log var x return to zero just once
and the question is, if input value with id duration more than 100, how looping, if each var x reach value (60) his return to zero and var c plus 1 each var x reach 60.
maybe anyone have an easier one to solve this case.
sorry if the explanation is unclear.

Timer not accurate [duplicate]

This question already has answers here:
How to create an accurate timer in javascript?
(15 answers)
Closed 6 years ago.
I am building an activity timer, but the code I have is not working properly. The timer is going ~40% faster than real time. What's going wrong?
var sec = 00;
var min = 00;
var hr = 00;
var t;
var timer_is_on = 0;
function timedCount() {
if (min == 0) {
min = 1;
}
document.getElementById('seconds').value = sec;
document.getElementById('minutes').value = min;
$('.node-form .form-item:nth-child(4) input').val(min);
document.getElementById('hours').value = hr;
$('.node-form .form-item:nth-child(3) input').val(hr);
sec = sec + 1;
if (sec == 60) {
sec = 0;
min = min + 1;
if (min == 60) {
min = 1;
hr = hr + 1;
}
}
t = setTimeout("timedCount()", 1000);
}
function doTimer() {
if (!timer_is_on) {
timer_is_on = 1;
timedCount();
}
}
function stopCount() {
clearTimeout(t);
timer_is_on = 0;
}
function resetCount() {
stopCount();
sec = 0;
min = 0;
hr = 0;
document.getElementById('hours').value = 00;
$('.node-form .form-item:nth-child(3) input').val('0');
document.getElementById('minutes').value = 00;
$('.node-form .form-item:nth-child(4) input').val('0');
document.getElementById('seconds').value = 00;
}
function putInTimelog() {
// Put hours
var hourItems = [];
var hourFields = document.getElementById("node-form").getElementsByTagName("input");
for (var i = 0; i < hourFields.length; i++) {
//omitting undefined null check for brevity
if (hourFields[i].id.lastIndexOf("edit-field-timelog-hours-0-value-", 0) === 0) {
hourItems.push(hourFields[i]);
}
}
var hourField = 'edit-field-timelog-hours-0-value-';
hourField = hourField.concat(hourItems.length);
document.getElementById(hourField).value = hr;
// Put minutes
var minuteItems = [];
var hourFields = document.getElementById("node-form").getElementsByTagName("input");
for (var i = 0; i < hourFields.length; i++) {
//omitting undefined null check for brevity
if (hourFields[i].id.lastIndexOf("edit-field-timelog-minutes-0-value-", 0) === 0) {
minuteItems.push(hourFields[i]);
}
}
var minuteField = 'edit-field-timelog-minutes-0-value-';
minuteField = minuteField.concat(minuteItems.length);
alert(minuteField);
alert((minuteField).length);
document.getElementById(minuteField).value = min;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<span class="timer-title"><strong>Activity timer</strong></span>h:
<input id="hours" readonly="readonly" size="2" type="text" /> m:
<input id="minutes" readonly="readonly" size="2" type="text" /> s:
<input id="seconds" readonly="readonly" size="2" type="text" /><span class="timer-buttons"><input onclick="doTimer()" type="button" value="Start" /> <input onclick="stopCount()" type="button" value="Stop" /> <input onclick="resetCount()" type="button" value="Reset" /> </span>
</form>
View on JSFiddle
clock.js is my repo that might help when used in conjunction with window.setInterval(). Working example included.
Add <script src="https://rack.pub/clock.min.js"></script> to your HTML then call clock.now --> 1462248501241 each time you want a time snapshot. You can add and subtract intuitively from there.
The actual js looks like:
var clock = (function() {
// object to expose as public properties and methods such as clock.now
var pub = {};
//clock.now
Object.defineProperty(pub, "now", {
get: function () {
return Date.now();
}
});
//API
return pub;
}());
var doc = document;
var el = doc.getElementById('output');
window.setInterval(function(){
/// call your function here
el.innerHTML = clock.what.time(clock.now);
}, 500);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rack.pub/clock.min.js"></script>
<h2 id='output'></h2>

How I can interpret the correct date in Javascript when the year is of the format yy?

I have defined an input that accepts only dates in HTML.
The user can enter the date manually or by using a Calendar which is defined in javascript.
I am using Javascript and Jquery to convert the input to a date:
var lStartDateText = $j("#DateStarte").val();
var lEndDateText = $j("#DateEnd").val();
var lEffStartDate = new Date(lStartDateText);
var lEffEndDate = new Date(lEndDateText);
My problem is that when the user enters the following date manually 1/1/50 is interpreted as 1/1/1950 but 1/1/49 is interpreted as 1/1/2049. I want it always to be interpreted as 20xx.
On the other hand the Calendar allows the user to choose a year from 2006 to 2021 in case the user wants to choose a date from it and not enter it manually.
Hope I can get some help here ??
Try this
var lStartDateText = $j("#DateStarte").val();
var lEndDateText = $j("#DateEnd").val();
var lEffStartDate = ReFormatDate(lStartDateText);
var lEffEndDate = ReFormatDate(lEndDateText);
function ReFormatDate(dateString) {
var dateParts = dateString.split("/");
if (dateParts[2].length === 2) {
dateParts[2] = "20" + dateParts[2];
}
return new Date(dateParts.join("/"));
}
use this
var lStartDateText = "1/1/50" ;
var lEndDateText = "1/1/49" ;
var res = lStartDateText.slice(4);
var starttext = lStartDateText.replace(res,"20"+res);
var res1 = lEndDateText.slice(4);
var endtext = lEndDateText.replace(res1,"20"+res1);
alert(starttext);
alert(endtext);
var lEffStartDate = new Date(starttext);
alert("start date"+lEffStartDate);
var lEffEndDate = new Date(endtext);
alert("End Date"+lEffEndDate);
If you know your getting the last 2 digits of the year (50), and you know you always want to add the first 2 digits, which are constant (20), that's a slight modification to your code:
var lStartDateText = '20' + $j("#DateStarte").val();
var lEndDateText = '20' + $j("#DateEnd").val();
Note that this is not particularly robust, e.g. if the user enters text which is not a date you might end up with a string like '20hi', but that may be outside the scope of your question and it will be parsed as an invalid date.
$('#year').on('change keyup', function() {
var y = $('#year').val();
if (y.length === 2) {
y = '20' + y
}
if (y.length === 4) {
var dateY = new Date();
dateY.setFullYear(y);
$('#result').html(dateY);
} else {
$('#result').html('No YY or YYYY date found');
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label for="year">Enter year (YY or YYYY)</label>
<input id="year" type="text">
<div id="result"></div>
i hope it's will be help you.
$('#year').on('change keyup', function() {
var right_date = $('#year').val();
var data = $('#year').val().split('/');
if (data[2].length == 2){
var twoDigitsCurrentYear = parseInt(new Date().getFullYear().toString().substr(0,2));
$('#result').html(data[0]+'/'+data[1]+'/'+twoDigitsCurrentYear + data[2]);
}
else {
$('#result').html(right_date);
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label for="year">Enter year (YY or YYYY)</label>
<input id="year" type="text" placeholder="dd/mm/yy">
<div id="result"></div>

JS is refusing to loop a function [duplicate]

This question already has answers here:
Calling functions with setTimeout()
(6 answers)
Closed 7 years ago.
I am having a problem with a countdown. I have made the countdown however the JS to change the HTML refuses to loop. I have a setInterval and I have tried for, while and do loops but none work. I would really appreciate some help.
HTML:
<body>
<center>
<h1> Input the date and time you want to countdown to!</h1>
<form>
Second:<input id="seconds" type="number"><br>
Minute:<input id="minutes" type="number"><br>
Hour:<input id="hours" type="number"><br>
Day:<input id="days" type="number"><br>
Month:<input id="months" type="text"><br>
Year:<input id="years" type="number"><br>
</form>
<button onclick="start()">Calculate!</button>
<h1 id="yearsres"></h1>Years<br>
<h1 id="monthsres"></h1>Months<br>
<h1 id="daysres"></h1>Days<br>
<h1 id="hoursres"></h1>Hours<br>
<h1 id="minutesres"></h1>Minutes<br>
<h1 id="secondsres"></h1>Seconds<br>
</center>
</body>
JS:
function start() {
var myVar = setInterval(test(), 1000)
}
function test() {
console.log("hi");
}
function calculateseconds(sec) {
var year = document.getElementById("years").value;
var month = document.getElementById("months").value;
var day = document.getElementById("days").value;
var hour = document.getElementById("hours").value;
var minute = document.getElementById("minutes").value;
var second = document.getElementById("seconds").value;
var countdownto = new Date(month + " " + day + "," + " " + year + " " + hour + ":" + minute + ":" + second);
var epochto = countdownto.getTime()/1000.0;
var current = new Date();
var epochcurrent = current.getTime()/1000.0;
var epochcountdown = epochto - epochcurrent;
var t = parseInt(epochcountdown);
var years = 0;
var months = 0;
var days = 0;
var i = 1;
if(t>31556926){
years = parseInt(t/31556926); t = t-(years*31556926);
}
if(t>2629743){
months = parseInt(t/2629743); t = t-(months*2629743);
}
if(t>86400){
days = parseInt(t/86400); t = t-(days*86400);
}
var hours = parseInt(t/3600);
t = t-(hours*3600);
var minutes = parseInt(t/60);
t = t-(minutes*60);
document.getElementById("yearsres").innerHTML = years;
document.getElementById("monthsres").innerHTML = months;
document.getElementById("daysres").innerHTML = days;
document.getElementById("hoursres").innerHTML = hours;
document.getElementById("minutesres").innerHTML = minutes;
document.getElementById("secondsres").innerHTML = t;
}
By adding () to your test function you call it. setInterval method takes a reference to the function (name of the function) and interval in milliseconds.
It can be used like this:
function start() {
var myVar = setInterval(test, 1000);
}
Or like this:
function start() {
var myVar = setInterval(function() {
test();
}, 1000);
}
Also if you need to pass parameters to your function you can do it like this:
function start() {
var myVar = setInterval(test, 1000, "First param", "Second param");
}
Remove () from test()
somehow it will work
https://jsfiddle.net/alesmana/u30zmj3t/

Categories

Resources