Vue Js Add timestamp when the checkbox is checked:To add a timestamp when a checkbox is checked in Vue.js, you can create a data property to store the timestamp value. Bind the checkbox input to a data property using the v-model
directive. Then, listen for the change
event on the checkbox and update the timestamp data property using the Date.now()
method when the checkbox is checked. You can display the timestamp in your template using double curly braces {{ timestamp }}
. Remember to initialize the timestamp as null
or an empty string in your data object
How can I add a timestamp when a checkbox is checked in Vue.js?
This Vue.js code snippet creates a checkbox component with two checkboxes. When a checkbox is checked, it updates the corresponding timestamp to the current date and time.
The checkbox state is managed using the v-model
directive, and the handleCheckboxChange
method is called on the @change
event to update the timestamp. The timestamp is displayed below each checkbox using the v-if
directive.
If the checkbox is checked, it shows the message “Checkbox [number] was checked at: [timestamp]”. If the checkbox is unchecked, the timestamp is reset to null.
Vue Js Add timestamp when the checkbox is checked Example
<div id="app">
<label>
<input type="checkbox" v-model="checkboxes[0].isChecked" @change="handleCheckboxChange(0)">
{{ checkboxes[0].label }}
</label>
<p v-if="checkboxes[0].isChecked">Checkbox 1 was checked at: {{ checkboxes[0].timestamp }}</p>
<label>
<input type="checkbox" v-model="checkboxes[1].isChecked" @change="handleCheckboxChange(1)">
{{ checkboxes[1].label }}
</label>
<p v-if="checkboxes[1].isChecked">Checkbox 2 was checked at: {{ checkboxes[1].timestamp }}</p>
</div>
<script type="module">
const app = new Vue({
el: "#app",
data() {
return {
checkboxes: [
{ label: "Check the box 1", isChecked: false, timestamp: null },
{ label: "Check the box 2", isChecked: false, timestamp: null }
]
};
},
methods: {
handleCheckboxChange(index) {
const checkbox = this.checkboxes[index];
if (checkbox.isChecked) {
checkbox.timestamp = new Date().toLocaleString(); // Set timestamp if checked
} else {
checkbox.timestamp = null; // Reset timestamp if unchecked
}
}
}
});
</script>