skip to Main Content

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 class="form-control" type="datetime-local" name="deliveryTime" id="DeliveryTime" required>
<input class="form-control" 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);
            
        });

2

Answers


  1. 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"))
      });
    
    Login or Signup to reply.
  2. 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:

    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 class="form-control" type="datetime-local" name="time1"><br>
    <input class="form-control" type="datetime-local" name="time2">
    </form>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search