I'm using Bootstrap Studio 5.3 to create a page with a form that has 22 fields in it.
One field is a "Date Updated" field that I'd like to have updated with the current date and time, any time something changed in one of the other fields (text inputs, select drop downs, check box group, textareas).
Currently, that Date Updated field is set to the date and time whenever the page loads.
How to detect any field change (except the Date Updated field), and then have the Date Updated field changed with the current date and time?
The JS:
//Account for timezones and formate date as mm/dd/yyyy HH:MM AM/PM
function getFormattedDateTime(date) {
const options = {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
hour12: false,
};
const formatter = new Intl.DateTimeFormat(undefined, options);
const formattedDateTime = formatter.format(date);
return formattedDateTime.replace(
/(\d+)\/(\d+)\/(\d+), (\d+):(\d+)/,
'$3-$1-$2T$4:$5'
);
}
const date = new Date(Date.now());
const formattedDateTime = getFormattedDateTime(date);
document.querySelector('#date_started').value= formattedDateTime;
document.querySelector('#date_updated').value= formattedDateTime;
Found something kinda similar here Detect change in form
However, that solution only applies to a "Submit" event.
Not sure how to convert that to when any field changes instead, and then how to pass that event...or somehow trigger the existing JS above to run again but only update the #date_updated field.
If you really need to track such changes, my first though is why don't you select all desired inputs in your form and for each input you track change
or input
event? For example:
const form = document.getElementById("myForm")
form.querySelectorAll("input").forEach(input =>{ //instead of just input as selector, you can use any other selector e.g. input[type="text"] only or input:not([type="checkbox"])
input.addEventListener("change", updateDateTime)
})
function updateDateTime(e){
//your code here...
}
You may also consider using input
event instead of change
, your call.
That seems doable to me. 22 inputs is not that many inputs to track performance-wise.
P.S.: You can also check this answer here: Entire form on change
Play with the best solution for you case.