Make the output of a span the value of an input - javascript

Good day all, i am building a form that uses javascript to get a client's local time which is correctly displayed in span element. However i wish to make the output of the span element the value of an input field in order to pass same into mysql. I tried php like below, it rather displays the code.
$currenttradetime = "<span id='digital-clock'></span>";
$currenttt = $currenttradetime;
?>
<input type='hidden' name="time" value="<?php echo $currenttt; ?>"></span>'>
Then using html/php, it equally displays the span html codes rather than the time. How do i achieve this?
function getDateTime() {
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth()+1;
var day = now.getDate();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
if(month.toString().length == 1) {
month = '0'+month;
}
if(day.toString().length == 1) {
day = '0'+day;
}
if(hour.toString().length == 1) {
hour = '0'+hour;
}
if(minute.toString().length == 1) {
minute = '0'+minute;
}
if(second.toString().length == 1) {
second = '0'+second;
}
var dateTime = hour+':'+minute+':'+second;
return dateTime;
}
// example usage: realtime clock
setInterval(function(){
currentTime = getDateTime();
document.getElementById("digital-clock").innerHTML = currentTime;
}, 1000);
The time is: <span id='digital-clock'></span>
<input type='text' value='<span id="digital-clock"></span>'>

Just use JavaScript to set the value of the input field like so:
function getDateTime() {
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth()+1;
var day = now.getDate();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
if(month.toString().length == 1) {
month = '0'+month;
}
if(day.toString().length == 1) {
day = '0'+day;
}
if(hour.toString().length == 1) {
hour = '0'+hour;
}
if(minute.toString().length == 1) {
minute = '0'+minute;
}
if(second.toString().length == 1) {
second = '0'+second;
}
var dateTime = hour+':'+minute+':'+second;
return dateTime;
}
// example usage: realtime clock
setInterval(function(){
currentTime = getDateTime();
document.getElementById("digital-clock").innerHTML = currentTime;
document.getElementById('time').value = currentTime;
}, 1000);
<span id="digital-clock"></span>
<input id="time" />

Change
<input type='hidden' name="time" value="<?php echo $currenttt; ?>"></span>'>
to have an id too and do not set the html as value for the input field:
<input id='digital-clock-inputfield' type='hidden' name="time" value=""></span>'>
then change
document.getElementById("digital-clock").innerHTML = currentTime;
to set the value of the input field too:
document.getElementById("digital-clock").innerHTML = currentTime;
document.getElementById("digital-clock-inputfield").value = currentTime;

Related

How can I find the difference between two time fields and add the result in the same document, inside a collection at MongoDB?

I am using the below function to add one row to the table. If user click Add-row button the below function will get called and one row will be added. In that row user have to enter start and end time .
Now my question is how to calculate the total time from that start and end time like we will calculate in Excel.
I know how they are doing in Excel but how to do the same thing in the table like this ?
I am using node + MongoDB for rendering pages.
var count=0;
function addRow(tableID) {
var id = "newlyaddedrow" + count;
var users = document.getElementById(tableID);
var row = `<tr class="info" style="cursor: pointer;background-color: #dbedf8;" id="${id}">
<td><input id="workAllocation_DateID" type="date" class="form-control" name="#date" value=""/></td>
<td><input type="text" class="form-control" name="#project_ID" value=""/></td>
<td><input type="text" class="form-control" name="#issue_Summary" value=""/></textarea></td>
<td><input type="text" class="form-control" name="#short_Description" value=""/></textarea></td>
<td><input type="time" class="form-control" name="#start_Time" value=""/></td>
<td><input type="time" class="form-control" name="#end_Time" value=""/></td>
<td><input type="time" class="form-control" name="#total_Time" value=""/></td>
</tr> `;
count++;
}
Below structure I have in mongoose collection.
And I want to calculate that total_time when the user enter start_time and end_time.
project_ID:"xxxx"
issue_Summary:"aaaa"
short_Description:"aaaa"
start_Time:"02:02"
end_Time:"03:02"
total_Time:""
_id:5d0ca14e138a7628948804af
date:2019-06-21 05:30:00.0001
Is there any way to do this? Can someone help me in this ?
As long as you store start_time and end_time as strings, you can parse them as dates and calculate the total time. Then convert back to string:
var start_Time = "02:02";
var end_Time ="03:05";
// Parsing as dates using a common date
var start_dt = new Date("1/1/1900 " + start_Time);
var end_dt = new Date("1/1/1900 " + end_Time);
// Calculate difference
var total_dt = end_dt - start_dt;
// Convert total_dt (which is in miliseconds) to hours and minutes
total_dt = total_dt/1000;
var sec = Math.floor(total_dt % 60);
total_dt = total_dt/60;
var min = Math.floor(total_dt % 60);
total_dt = total_dt/60;
var hours = Math.floor(total_dt % 24);
console.log( hours +":" + min)
I have tried with event and it's working perfect.
This event is happening onblur() of the that particular column in the row
function calculateTime(){
var startTime = new Date();
var endTime = new Date();
var totalTime = new Date();
var startTimeStr = '';
var endTimeStr = '';
var totalTimeStr = '';
if(event.target.name == '#start_Time' && event.target.value != ''){
startTimeStr = event.target.value;
if((event.target.parentElement.nextElementSibling.firstElementChild).value != ''){
endTimeStr = (event.target.parentElement.nextElementSibling.firstElementChild).value;
}
}else if(event.target.name == '#end_Time' && event.target.value != ''){
endTimeStr = event.target.value;
if((event.target.parentElement.previousElementSibling.firstElementChild).value != ''){
startTimeStr = (event.target.parentElement.previousElementSibling.firstElementChild).value;
}
totalTimeStr = (event.target.parentElement.nextElementSibling.firstChild);
}
if(startTimeStr != '' && endTimeStr!= ''){
startTime = startTime.setHours(startTimeStr.split(':')[0],startTimeStr.split(':')[1]);
endTime = endTime.setHours(endTimeStr.split(':')[0],endTimeStr.split(':')[1]);
if(startTime > endTime){
alert('End time cannot be before start time!!!');
}else{
totalTime = endTime - startTime;
var hours = Math.floor(((totalTime / (1000*60*60)) % 24));
var minutes = Math.floor(((totalTime / (1000*60)) % 60));
totalTimeStr.value = hours +':'+ minutes;
console.log('Total Time' +totalTimeStr);
}
}
}

multiple alarm clock in javascript using dynamic generated input elements in 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>

How to stop incorrect value in datepicker when previous data select in JavaScript?

Here, I got code for disable date in datepicker. when user select previous date then it alert to put a valid future date. It's working.
But It's printing whatever we select previous date. I want to stop print when previous date select. Thanks in advance.
<div class="col-md-8">
<input class="form-control datepicker" id="datepicker" onchange="checkDate()" required type="date" name="smexdate" value="<?=$promotion_details['expiry_date']?>" data-date-format="yyyy-mm-dd">
</div>
and JavaScript below.
function checkDate() {
var selectedText = document.getElementById('datepicker').value;
var selectedDate = new Date(selectedText);
var now = new Date();
if (selectedDate < now)
{
alert("Date must be in the future");
return false;
}
}
How about this?
var lastData;
function checkDate() {
var selectedText = document.getElementById('datepicker').value;
var selectedField = document.getElementById('datepicker');
var selectedDate = new Date(selectedText);
var now = new Date();
if (selectedDate < now)
{
console.log(lastData)
selectedField.value = (lastData) ? lastData : '';
alert("Date must be in the future");
return 0;
}
var theDate = new Date(selectedText);
var month = theDate.getMonth() + 1;
var date = theDate.getDate();
var year = theDate.getFullYear();
lastData = year + "-" + String("0" + month).slice(-2) + "-" + String("0" + date).slice(-2);
}

How to separate regex in javascript Hours format

I have some problem to define hours time, i want to separate hours time to 3 time type morning, evening, and night.
if time start from 00:00 to 10:00 the type time is morning,
if time start from 10:01 to 18:00 the type time is evening,
if time start from 18:01 to 23:59 the type time is night,
i have code jquery like this
$(document).ready(function(){
$('#submit').on('click',function(){
var hrs=$('#hours').val();
var nm=$('#scedule').val();
var patt = new RegExp("^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$");
var patts = patt.test(hrs);
//morning = 00:00 - 10:00
var morn = new RegExp("^([0-9]|0[0-9]|1[0-9]):[0-5][0-9]$");
var morning = morn.test(hrs);
//evening = 10:01 - 18:00
var even = new RegExp("^(1[0-9]|[0-9]):[0-5][0-9]$");
var evening = even.test(hrs);
//night = 18:01 - 00:00
var nig = new RegExp("^(1[0-9]|2[0-3]):[0-5][0-9]$");
var night = nig.test(hrs);
if ( patts == morning ) {
alert('This is Morning');
} else if (patts == evening){
alert('This is Evening');
} else if (patts == night){
alert('This is night');
} else {
alert('Format is wrong');
}
});
});
and this is my form HTML :
Scedule : <input type="text" id="scedule"><br>
Time : <input type="text" id="hours"><br>
<input type="submit" value="submit" id="submit"><br>
You don't need a regex here, just use Date:
$(document).ready(function(){
$('#submit').on('click',function(){
var hrs=$('#hours').val();
if(hrs.length != 5 || hrs.indexOf(':') < 0)
{
alert("Wrong Fromat")
return;
}
var date = new Date();
date.setHours(hrs.split(":")[0]);
date.setMinutes(hrs.split(":")[1]);
console.log(date)
if ( date.getHours() < 10) {
console.log('This is Morning');
} else if (date.getHours() > 18 && date.getMinutes > 0){
console.log('This is night');
} else{
console.log('This is Evening');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
Time : <input type="text" id="hours"><br>
<input type="submit" value="submit" id="submit"><br>

Run function for 30 min

Here's what I want to do.
Execute a function : once, at some time of the day.
The function run for 30 minutes.
I've tried setTimeout but it doesn't fit my requirement because it run the function after X millisecond. Whereas I need the function to execute right away, at desired time for 30 minutes. Code as attached.
var d = new Date();
var hour = d.getHours();
var minute = d.getMinutes();
var day = self.getDate();
var month_name=new Array(12);
month_name[0]="January"
month_name[1]="February"
month_name[2]="March"
month_name[3]="April"
month_name[4]="May"
month_name[5]="June"
month_name[6]="July"
month_name[7]="August"
month_name[8]="September"
month_name[9]="October"
month_name[10]="November"
month_name[11]="December"
var month = month_name[self.getMonth()];
var fullDate = month+' '+day+' '+hour+':'+minute;
function someFunction() {}
function closeFunction(){
noticeDiv.css('display', 'block');
mainDiv.css('display', 'none');
}
function executeFunction(targetDate){
if (fullDate == targetDate){
setTimeout ( closeFunction(), 180000 );
}else{
someFunction();
}
}
executeFunction(targetDate);
Use setInterval Function
Syntax-> var interval = setInterval(function(){function_name()},timeout In milliseconds);
To clear Interval or stop function we use ->clearInterval(interval);
HTML
<!-- Hide by default, show at target time -->
<div id="noticeDiv" style="display: none">
<h2>Registration Closed.</h2>
</div>
<!-- Show by default, hide at target time -->
<div id="mainDiv">
<h2>Registration Open.</h2>
</div>
jQuery
$(document).ready(function () {
var d = new Date();
var hour = d.getHours();
var minute = d.getMinutes();
var day = d.getDate();
var month_name = new Array(12);
month_name[0] = "January"
month_name[1] = "February"
month_name[2] = "March"
month_name[3] = "April"
month_name[4] = "May"
month_name[5] = "June"
month_name[6] = "July"
month_name[7] = "August"
month_name[8] = "September"
month_name[9] = "October"
month_name[10] = "November"
month_name[11] = "December"
var month = month_name[d.getMonth()];
var fullDate = month + ' ' + day + ' ' + hour + ':' + minute;
console.log(fullDate);
fulldate = 'May 3 17:1';
function executeFunction(targetDate) {
x = 0;
if (fulldate == targetDate) {
//set closing time of function 180000 = 30 min.It will hide div registration open and show registration closed div.
interval = setInterval(closeFunction, 180000);
} else {
openFunction();
}
}
function openFunction() {
console.log('Registration is now open')
}
function closeFunction() {
x++;
$('#mainDiv').append(x);
if (x == 1) {
$('#noticeDiv').show();
$('#mainDiv').hide();
clearInterval(interval);
}
}
// Execute time
executeFunction('May 3 17:1');
});
Working Demo http://jsfiddle.net/cse_tushar/8r5T8/

Categories

Resources