Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Calculadora

0

143
Vistas
Vue 3 Composition API - Disabling form submit button until all conditions are met

I want to disable my form submit button until all the input fields are filled in and there are no errors.

<button
  :disabled="disabled"
  type="submit"
  value="Submit"
  >
  Suggest
</button>

let disabled = ref(true);
let error = ref(false);

nextTick(() => {
  let inputs = Array.from(document.getElementsByClassName("form__input"));
  if (!error.value) {
    inputs.forEach((input) => {
      if (input.value === "") {
        disabled.value = true;
      } else {
        disabled.value = false;
      }
    });
  }
})

The button is disabled by default but it won't 'enable' itself once the already mentioned conditions are met.

So far, I'm using a helper lifecycle hook nextTick() which clearly doesn't help me in this situation.

The 'disabled' state will update in the console but not on the DOM.

How can I approach this?

Cheers

7 months ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

The easiest solution is by using a computed value to set the disabled state of the button - based on the input values - if any are empty, button is disabled

Here's a basic example

const { ref, createApp, computed } = Vue;
createApp({
    setup() {
        const input1 = ref("");
        const input2 = ref("");
        const input3 = ref("");
        // disabled is true if ANY input is empty string
        const disabled = computed(() => !input1.value || !input2.value || !input3.value);
        const clicked = () => console.log('clicked');
        return { input1, input2, input3, disabled, clicked };
    }
}).mount('#app');
<script src="https://unpkg.com/vue@3.2.37/dist/vue.global.prod.js"></script>
<div id="app">
  Input 1: <input v-model="input1" type="text"/><br/>
  Input 2: <input v-model="input2" type="text"/><br/>
  Input 3: <input v-model="input3" type="text"/><br/>
  <button :disabled="disabled" @click="clicked">Click me</button>
</div>

7 months ago · Juan Pablo Isaza Denunciar

0

maybe you should use v-model,computed or @input to listen event and change button disable status.

7 months ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar empleo Planes Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2023 PeakU Inc. All Rights Reserved.