I have datetime-local html control on my form and I need to set date and time on it dynamically via JS or jQuery. How can I do it?
If you want to set the current date, then you can try this:
__Method 1:__
$(document).ready(function(){
$('input[type=datetime-local]').val(new Date().toJSON().slice(0,19));
});
__Method 2:__
function zeroPadded(val) {
if (val >= 10)
return val;
else
return '0' + val;
}
$(document).ready(function(){
d = new Date();
$('input[type=datetime-local]').val(d.getFullYear()+"-"+zeroPadded(d.getMonth() + 1)+"-"+zeroPadded(d.getDate())+"T"+d.getHours()+":"+d.getMinutes()+":"+d.getSeconds());
});
Note: You can replace $('input[type=datetime-local]') with Id
or Name
or Class
of the datetime-local field.
EDIT: d.getMonth() returns a value between 0-11, so to input the proper month 1 needs to be added to the result.