Home > Net >  Vue Prevent form submit when pressing enter inside form
Vue Prevent form submit when pressing enter inside form

Time:11-30

I have a webapp with multiple forms and inside these forms multiple custom made components: input, textarea, selectbox, datepicker, radiobutton, checkbox, ... .

I found out that the submit function is fired when pressing the enter key inside a child component of a form tag. Something I don't want. I want to be able to use the enter key for other things like conforming a selection in a dropdown.

Form example

<template>
    <form @submit.prevent="handleLogin">
        <fieldset :disabled="isSubmitting" class="space-y-6">
            <Input :label="$tc('email', 1)" type="email" id="email" v-model="user.email" :error="errors.email" />
            <Input :label="$tc('password', 1)" type="password" id="password" v-model="user.password" :error="errors.password" />
            <Select :label="$tc('role', 1)" id="role" :options="roles" displayProperty="display_name" valueProperty="id" v-model="user.role" :error="errors.role" />
            <SubmitButton :label="$tc('register', 1)" :submittingLabel="$tc('register_loader', 1)" :isSubmitting="isSubmitting" />
        </fieldset>
    </form>
</template>

SubmitButton.vue

<button type="submit">{{ isSubmitting ? submittingLabel : label }}</button>

Therefore I'm looking for a way to prevent the default behaviour. Adding a keydown function and checking if the enter key is being pressed inside all the custom components followed by an event.preventDefault() didn't do the trick.

A working solution should be to change the type of the button from 'submit' to 'button' and use an @click but that doesn't sound like semantic html.

Any other suggestions?

CodePudding user response:

You can prevent submission on enter key down just annotating the top-level form.

<form @submit.prevent="handleLogin" @keydown.enter="$event.preventDefault()">

You can see it in action

  • Related