HTML5 input=time won't set via javascript - javascript

I am having a problem with an HTML5 form field, I need the field (time) to update each second to the current time, the update code is called every second via a setInterval, the HTML5 form element :
<form name="process">
<input name="p_time" type="time" value="<?php echo date("H:i:s");?>" />
//...
</form>
when I try to update : document.forms.process.p_time.value = current.time.slice(17,25); the display remains at the setting made by PHP, the type of string data is the same format of 00:00:00 but it refuses to budge from that original time. the variable current.time is a string of the UTC format corresponding to : ddd, dd mmm, yyyy hh:mm:ss +00:00 GMT variety.
The javascript is a simple routine, it updates a element in the full version
current = {
now:function(){ return new Date(); },
time:0,
tick:function(){
current.time = current.now().toUTCString();
document.forms.process.p_time.value = current.time.slice(17,25);
current.clock();
},
clock:function(){
current.target.innerHTML = current.time.slice(0,25);
},
auto:setInterval(current.tick,1000)
}
What I don't want to have to do is to have the page refreshed by a page refresh.

This should work!: http://jsfiddle.net/d9vg5yhL/1/
<form name="process">
<input name="p_time" id='time' type="time" value="" />
</form>
Javascript:
function startTime() {
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
h = checkTime(h);
m = checkTime(m);
s= checkTime(s);
document.getElementById('time').value = h+":"+m+":"+s;
var t = setTimeout(function(){startTime()},1000);
}
function checkTime(i) {
if (i<10) {i = "0" + i} // add zero in front of numbers < 10
return i;
}
startTime();

Related

Select a date 7 days after current date in javascript

I have input in html like this:
<input class="form-control" placeholder="Date of Collection *" id="m_date" name="m_date" type="date" tabindex="6" required/>
I would like to select a date that is more than 7 days from the current date, if I select a date before 7 days from current, it should prompt saying "Wrong date selected"
How do I do that in javascript?
I tried the following:
var date = new Date();
date.setDate(date.getDate() + 7);
console.log(date);
It gives the date correctly. How do I use this to compare if date is 7 after or not and prompt accordingly?
Thanks!
UPDATE:
<html>
<body>
<input class="form-control" placeholder="Date of Collection *" id="m_date" name="m_date" type="date" tabindex="6" required/>
</body>
</html>
<script>
let cal = document.body.getElementsByClassName('form-control')[0];
cal.onchange = function(e)
{
var selectDate = e.target.value
var startDate = new Date(Date.parse(selectDate));
console.log(startDate);
var dateAfter7Days = new Date(new Date().getTime()+(7*24*60*60*1000))
console.log("7 days " + dateAfter7Days);
if (startDate => dateAfter7Days )
{
console.log("Allow");
}
else
{
console.log("Don't allow");
}
}
</script>
I am getting "Allow" for any date I select.
The point is comparing two date values. If current date - selected date > 7 then it should print prompt. The problem is how to get selected date.
You can get the selected date from the input tag by event value. On changed date, the value get logged.
let cal = document.body.getElementsByClassName('form-control')[0];
cal.onchange = function(e) {
console.log(e.target.value);
}
<input class="form-control" placeholder="Date of Collection *" id="m_date" name="m_date" type="date" tabindex="6" required/>
var date = new Date();
var next_seven_date = d.getDate()+7;
var current_month = d.getMonth();
current_month++; // month start from 0 then we need to +1
var current_year = d.getFullYear();
var weekDate =(next_seven_date + "/" + current_month + "/" + current_year);
date.setDate(weekDate);
Since your problem is to compare dates not creating them I have updated my answer which might hlp you
var currentDate= new Date();
currentDate= new Date(currentDate.getFullYear(),currentDate.getMonth(),currentDate.getDate(),0,0,0)
var idealDifference= (7*24*60*60*1000);
//In your case this date might comes from some date selection user control. Be aware to make the time part of each date to same
var userSelectedDate = new Date(2021, 04, 04,currentDate.getHours(),0,0,0)
if((userSelectedDate.getTime()-currentDate.getTime())>=idealDifference)
{
console.log(userSelectedDate, ' is after 7 days from ',currentDate)
}
else
{
console.log(userSelectedDate, ' is before 7 days from ',currentDate)
}
Note: It is important to unset the time part of both the dates before comparing for this logic to work

How convert input type="date" in a timestamp?

I need to convert an <input type="date"> value in a timestamp. This is my HTML code:
<input type="date" name="date_end" id="date_end">
This field has a value that I have put like 25/10/2017
My jQuery code is:
var dataEnd = $('[name="date_end"]').val();
if (!dataEnd) {
return false;
} else {
var timestamp_end=$('[name="date_start"]').val().getTime();
console.log("TIMESTAMP END "+timestamp_end);
.....
}
But this is not working... why not?
make a new Date() passing the value of your input as parameter, then call getTime(). here an example:
$('[name="date_end"]').on('change',function() {
var dataEnd = $(this).val();
console.log((new Date(dataEnd)).getTime());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="date" name="date_end" id="date_end">
do this
var dateEnd = $('#date_end').val()
var var timestamp_end = Date.parse(date_end)
or
in a single line
var timestamp_end = Date.parse($('#date_end').val())
it works and it's clean
Here is a Solution ( Using pure js ) , I used the unary plus operator operator after converting the value into javascript date object.
function checkDateValue(){
var dateConvertedToTimestamp = (+new Date(document.getElementById('date_value').value));
document.getElementById('date_value_timestamp').innerHTML = dateConvertedToTimestamp ;
}
<input type='date' id='date_value'>
<button onClick='checkDateValue()'> Submit </button>
<div>Timestamp:- <span id='date_value_timestamp'></span></div>
I needed an UNIX timestamp and updated Partha Roy's anwser for my needs.
Javascript :
document.getElementById('dateInput').addEventListener('change', function (){
let inputDate = document.getElementById('dateInput').value ;
let dateConvertedToTimestamp = new Date(inputDate).getTime() ;
console.log(dateConvertedToTimestamp) ;
document.getElementById('resultTime').value = dateConvertedToTimestamp / 1000 ;
}) ;
The /1000 division convert to UNIX timestamp + I track all input change and not only when the form is submited.
HTML :
<input type='date' id='dateInput'>
<input type='hidden' id='resultTime' name='dateTimestamp'>
Don't forget date input are still not well supported, so we can easily adapt this code with classic numbers input.
You can use following code
<script type="text/javascript">
var d = new Date(parseInt($('[name="date_start"]').val()));
var n = d.getTime();
console.log(n);
</script>

Change the value of a public variable javascript

I want to change the value of a public variables with a function and use this new values from an other function.
My use case: I want to set a default public variable for a countdown timer, and if the user wants to change the target date he could put a new date. To do so, I've created another function to change the public variables, but it doesn't seem to work perfectly.
Here is my code:
<table id="global" border="3">
<tr>
<td align="center">
<form name="formInput" action="#">
<label>Choose new Date: </label>
<input type="date" name="field1" Id="txtvarInput" />
<br />
<br />
</label>
<div class="form-actions" "span3">
<input name="submit" type="submit" class="btn" value="Select" onclick="alertVal()" />
</div>
</form>
</td>
</tr>
<tr id="countdownTimer">
<td>
<script type="application/javascript">
var current = "Has been launched!"; //-->enter what you want the script to display when the target date and time are reached, limit to 20 characters
var year;
var month;
var day;
var hour = 0;
var minute = 0;
var second = 0;
var ampm = "pm";
var timezone = -5;
function alertVal() {
var theInput = document.getElementById('txtvarInput').value;
var date_array = new Array();
date_array = theInput.split("-");
month = date_array[1];
year = date_array[0];
day = date_array[2];
}
var Countdown_Ignition = new Countdown({
width: 300,
height: 60,
year,
month,
day,
hour,
ampm,
minute,
second,
timezone,
rangeHi: "day",
style: "flip" // <- no comma on last item!!
});
</script>
</td>
The issue is that when I change the date, my second function doesn't take the new values.
this doesn't work because you're passing a value on the object literal (pointing to undefined at first), so when your alertVal function "updates" the value, it's making an assignment pointing to the new value (i.e. 22).
If you want to keep track of the change inside the Countdown object, you have to pass a variable which points to an actual object (a reference, not a value). So, your global function updates a property of the very same object and you win!
var publicObject = {
year: null,
day: null,
etc: null
};
function setData(){
publicObject.day = 'new value';
publicObject.year = 'new value';
publicObject.etc = 'and so on';
};
var Countdown_Ignition = new Countdown({
width:300,
height:60,
publicObject,
rangeHi:"day",
style:"flip" // <- no comma on last item!!
});

Add one hour to string on client side

I have two timepicker in my view
#Html.Kendo().TimePickerFor(m=>m.AttendeeStartTime).Format("HH:mm")
#Html.Kendo().TimePickerFor(m=>m.AttendeeEndTime).Format("HH:mm")
This is how it looks
and here is rendered HTML for From Timepicker,
<input data-val="true" data-val-required="The AttendeeStartTime field is required."
id="AttendeeStartTime" name="AttendeeStartTime" type="text" value="09:00" data-role="timepicker"
class="k-input valid" role="textbox" aria-haspopup="true" aria-expanded="false" aria-
owns="AttendeeStartTime_timeview" aria-disabled="false" aria-readonly="false" style="width: 100%;">
Whenever there is change in From timepicker, how can I add one hour to its value and set to to To timepicker?
This is what I have done,
$('##Html.IdFor(m=>m.AttendeeStartTime)').on('change', function () {
//var date = new Date();
endTime.value($(this).val());
alert(endTime.value());
This only sets the To value to the same as From when there is change, but I want to add an hour or some timespan to it.
How should i do that?
Use this:
$('##Html.IdFor(m=>m.AttendeeStartTime)').on('change', function () {
//try getting the date from the date picker
var date = $("##Html.IdFor(m=>m.AttendeeStartTime)").data("kendoTimePicker").value();
if (date) {
//convert the string to a date
date = new Date(date); //you can probably skip this step since the Kendo DatePicker returns a Date object
//increase the "hours"
date.setHours(date.getHours() + 1);
//set it back in the "to" date picker
$("##Html.IdFor(m=>m.AttendeeEndTime)").data("kendoTimePicker").value(date);
//alert(endTime.value());
}
}
You can write a custom function like this,
function addMinutes(time, minsToAdd) {
function z(n){ return (n<10? '0':'') + n;};
var bits = time.split(':');
var mins = bits[0]*60 + +bits[1] + +minsToAdd;
return z(mins%(24*60)/60 | 0) + ':' + z(mins%60);
}
addMinutes('05:40', '20'); // '06:00'
addMinutes('23:50', 20);
Your scenario should be,
$('##Html.IdFor(m=>m.AttendeeStartTime)').on('change', function () {
//var date = new Date();
endTime.value($(this).val());
addMinutes($(this).val(), '60');
alert(endTime.value());

Validation with KendoUI datetime

Hi i have an app where user can select for start datetime and end datetime if they want to create an event.
Now this is an html where i use KendoUI datetime plugin:
<div class="demo-section" style="width: 535px;">
<label for="start">Start date:</label>
<input id="start" value="01/01/2013" />
<label for="end" style="margin-left:3em">End date:</label>
<input id="end" value="01/01/2013"/>
</div>
</li>
<script type="text/javascript">
$(document).ready(function(){
function startChange() {
var startDate = start.value();
if (startDate) {
startDate = new Date(startDate);
startDate.setDate(startDate.getDate());
end.min(startDate);
}
}
function endChange() {
var endDate = end.value();
if (endDate) {
endDate = new Date(endDate);
endDate.setDate(endDate.getDate());
start.max(endDate);
}
}
var start = $("#start").kendoDateTimePicker({
change: startChange,
parseFormats: ["MM/dd/yyyy"]
}).data("kendoDateTimePicker");
var end = $("#end").kendoDateTimePicker({
change: endChange,
parseFormats: ["MM/dd/yyyy"]
}).data("kendoDateTimePicker");
start.max(end.value());
end.min(start.value());
});
Issues is i cant get validation as i want. Suppose user select From date the To date should display date which is greater that currently selected From date.My currrent code seems not works well. Thanks
Are you saying that you want to be able to select a From date greater than To, and that when you do To should automatically update to be greater than From?
If so you're almost there. You just need to update the startChange function to update the To date relative to From.
function startChange() {
var startDate = start.value();
if (startDate) {
startDate = new Date(startDate);
startDate.setDate(startDate.getDate());
end.min(startDate);
var endDate = end.value();
if (endDate && endDate <= startDate) {
endDate.setDate(startDate.getDate() + 1);
end.value(endDate);
}
}
}
Check this jsFiddle for a full working example.

Categories