search

Home  >  Q&A  >  body text

How to set default value for input field of datetime native type dynamically created using Vuejs/Nuxtjs?

I am dynamically creating some datetime-local type input fields in Vuejs/Nuxtjs. I want to set the default value of all these input fields to 2022-04-21T14:27:27.000. How to do it?

For direct fields we can assign values ​​using v-model but I'm a bit unsure how to set default values ​​for all fields of datetime-local. If I remember correctly, there is an option in vanilla JavaScript to get all fields of a certain type and change the values, is there a way to achieve the same using Vuejs/Nuxtjs.

Here is my code so far:

<template>
  <div>
    <button type="button" @click="addField" class="btn btn-info">
      Add Field
    </button>

    <div v-for="field in fieldArray" :key="field.ID" class="form-group">
      <input
        v-model="field.time"
        type="datetime-local"
        class="form-control"
        step="1"
        value="2022-04-21T14:27:27.000"
        @change="timeChange(field.ID)"
      />
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      fieldCount: 0,
      fieldArray: [],
    };
  },
  mounted() {
    let now = new Date();
    now.setMinutes(now.getMinutes() - now.getTimezoneOffset());
    now.setSeconds(now.getSeconds(), 0);
    now = now.toISOString().slice(0, -1);
    //I would like to set this "now" time value for all the created fields of input type datetime-local
    console.log("Current Time : " + now);
  },
  methods: {
    //Add field
    addField() {
      const fieldObj = { ID: this.fieldCount, time: "" };
      this.fieldArray.push(fieldObj);
    },
    //Time change
    timeChange(ID) {
      console.log("ID : " + ID);
      console.log(JSON.stringify(this.fieldArray, null, 4));
    },
  },
};
</script>

<style>
</style>

What I want to do is set a default time for all datetime-local fields in my component. Is there any way to do this? I can achieve this with a single field, but not with a dynamically created field.

P粉156983446P粉156983446233 days ago495

reply all(1)I'll reply

  • P粉138871485

    P粉1388714852024-04-01 11:06:18

    Is it similar to this?

    
    
    sssccc
    
    

    reply
    0
  • Cancelreply