I have two datetime-local input star time is for user changeable and the other one is read-only and I want to update that field by jquery.
<input type="datetime-local" name="deliveryTime" id="DeliveryTime" required>
<input type="datetime-local" name="deliveryTimeEnd" id="DeliveryTimeEnd" readonly>
$("#DeliveryTime").on("change", function() {
var startTime = $("#DeliveryTime").val();
startTime.setHours(startTime.getHours() 2);
alert(startTime);
$("#DeliveryTimeEnd").val(startTime);
});
CodePudding user response:
first chnage the startTime in datetime format like below code and then get the hours
var dt = new Date(startTime);
dt.setHours(dt.getHours() 2);
Complete code is:
$("#DeliveryTime").on("change", function() {
var startTime = $("#DeliveryTime").val();
alert(startTime);
var dt = new Date(startTime);
dt.setHours(dt.getHours() 2);
alert(dt.toLocaleString("sv-SE"));
$("#DeliveryTimeEnd").val(dt.toLocaleString("sv-SE"))
});
CodePudding user response:
In the end it was not quite as trivial as I assumed in the beginning. Here is a snippet that sets the second datetime input to a time 2 hours after the time of the first input:
Date.prototype.add=function(n,unit){ this["set" unit]( this["get" unit]() n); return this;}
abc.time1.addEventListener("input",ev=>{
const dt=new Date(abc.time1.value);
dt.setMinutes(dt.getMinutes()-dt.getTimezoneOffset() 120);
abc.time2.value=dt.toISOString().slice(0,-5);
});
<form name="abc">
<input type="datetime-local" name="time1"><br>
<input type="datetime-local" name="time2">
</form>