I want to disable the form submit button until all 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 will not "enable" itself once the conditions already mentioned are met.
So far I'm using a secondary lifecycle hook nextTick()
which obviously doesn't help me in this case.
The "disabled" status will be updated in the console, but not on the DOM.
How can I solve this problem?
cheers
P粉1808446192023-11-14 00:30:04
Maybe you should use v-model
, compulated
or @input
to listen to events and change the button disabled state.
P粉8284636732023-11-14 00:15:17
The simplest solution is to set the disabled state of the button using a calculated
value - based on the input value - if any are empty, the button is disabled
This is 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');
ssscccInput 1:
Input 2:
Input 3: