ΩmegaMan
ΩmegaMan

Reputation: 31576

Set an Initial Time String to an Input Element Using JQuery

I have an input element of type time on my page which I save off the user time selection in the format which was given 12:22. But I am having trouble loading the time 12:22 string back into the element on a return session.

How does one load the time, and show the time, in a type input element?


Element

<input type="time" id="Time1"/>

I've tried

$('#Time1').val = '3:22';

and

$('#Time1').value = '3:22';

with no luck.


My initial value in the config file (not set by the user) had a value of 3 and should be 03. I am marking the answers related to the first problem of assignment and not the loading value which has to be XX not X.

Upvotes: 1

Views: 40

Answers (2)

Negi Rox
Negi Rox

Reputation: 3922

you can do this by the below code.

function AssignTime() {
   
   var d = new Date();
  document.getElementById("Time1").value = d.toLocaleTimeString(navigator.language, {hour: '2-digit', minute:'2-digit'}).split(" ")[0];//time should be in 24 hrs format.
}
Time: <input type="time" id="Time1">
<button onclick="AssignTime()">Assign</button>

Upvotes: 1

Spectric
Spectric

Reputation: 31987

The value property does not exist in a jQuery object. Use the val() method:

$('#Time1').val('12:22');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="time" id="Time1"/>

Upvotes: 1

Related Questions