I have the following script:
$('input[name=flexRadioDefault]:radio').click(function () {
let datecreated = new Date();
let servicetime = new Date();
if($('#flexRadioDefault2').is(':checked')) {
datecreated = datecreated.getFullYear()+'-'+(datecreated.getMonth()+1)+'-'+datecreated.getDate()
servicetime = servicetime.getHours() + ':' + servicetime.getMinutes();
console.log(datecreated);
console.log(servicetime);
console.log("checked");
$('#servicedate').val(datecreated);
$('#servicedate').prop('disabled',true);
$('#servicetime').val(servicetime);
$('#servicetime').prop('disabled',true);
console.log($('#servicedate').val());
}
else {
$('#servicedate').val('');
$('#servicetime').val('');
$('#servicetime').prop('disabled',false);
$('#servicedate').prop('disabled',false);
}
})
HTML:
<h5>Service Period:</h5>
<div class="form-check">
<input class="form-check-input" type="radio" name="flexRadioDefault" id="flexRadioDefault1" checked>
<label class="form-check-label" for="flexRadioDefault1">
Scheduled
</label>
</div>
<div class="form-check">
<input class="form-check-input" type="radio" name="flexRadioDefault" id="flexRadioDefault2">
<label class="form-check-label" for="flexRadioDefault2">
Immediate
</label>
<br>
</div>
<div class="servicedate col-md-6">
<div class="form-group">
<label for="start">Service date:<span class="text-danger">*</span></label>
<input type="date" id="servicedate" name="servicedate" placeholder = "mm/dd/yyyy" required>
</div>
<div class = "form-group">
<label for="start">Service time:<span class="text-danger">*</span></label>
<input type="time" id="servicetime" name="servicetime" required>
</div>
</div>
Here is how the thing look like:
So if user select Scheduled
, the date and time must be manually selected. If Immediate
, the script will extract the current date and time and put it in the input box of servicetime
and servicedate
.
But the problem is the code is not stable. I am unsure why but sometime when I clicked Immediate
, only the current time is shown in servicetime
. The date does not show. Sometime both the current time and date is no where to be found in the input box. While it does not show in the input box, the console is still printing the current time and date. Can anyone explain to me what am I doing wrong and point out how can I fixed this? Thank you !