Skip to content
Advertisement

Vue.js – Disable submit button unless original form data has changed

I have a simple form which I have created just for experiment purpose. I am trying to keep the button disable unless original form data is changed but still keep the button disabled if the data changes is reverted back to original data (undo).

<template lang="pug">
  form(@click.prevent="save")
    .main
      input(v-model="user.name")
      input(v-model="user.email")
      input(v-model="user.age")
      select(v-model="user.sex")
        option Male
        option Female
    .footer
      button(:disabled="isFormEnable") Save
</template>

<script>
export default {
  name: 'userForm',
  data () {
    return {
      user: {
        name: 'John Doe',
        email: 'john@gmail.com',
        age: '35',
        sex: 'Male',
      }
    }
  },

  computed: {
    isFormEnable () {
      // I am not sure what I need to do here but something like this may be:
      if (user.name) { return true }
    }
  },

  methods: {
    save () {
      console.log('Form Submitted')
    }
  }
}
</script>

I found a jQuery solution here but I am looking for vanilla/vue javascript solution.

$('form')
    .each(function(){
        $(this).data('serialized', $(this).serialize())
    })
    .on('change input', function(){
        $(this)             
            .find('input:submit, button:submit')
                .prop('disabled', $(this).serialize() == $(this).data('serialized'))
        ;
     })
    .find('input:submit, button:submit')
        .prop('disabled', true)
;

Advertisement

Answer

Here’s how i would do it with the help of 1 module

npm i deep-diff

deep-diff is for comparing object values.

<script>
import { diff } from "deep-diff";

// default form value
const defaultUser = {
  name: "John Doe",
  email: "john@gmail.com",
  age: "35",
  sex: "Male"
};

export default {
  //...
  data() {
    return {
      user: { ...defaultUser } // cloning the object using object spread syntax
    };
  },

  computed: {
    isFormEnable() {
      // check if it's default value
      if (!diff(this.user, defaultUser)) return false;

      return true;
    }
  },
  //...
};
</script>
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement