Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

garrettmassey's avatar

@keyup.enter and @click both triggering

I have a small message form on my project, and I want the form to submit EITHER when the user hits enter on the input, OR when the user clicks the "send" button.

<template>
    <form @submit.prevent="submit">
        <div class="input-group">
            <input type="text"
                   class="form-control type_msg"
                   placeholder="Type your message..."
                   v-model="form.message"
                   @keyup.enter="sendMessage()"
            >
            <input type="hidden" v-model="form.conversationID">
        <button class="btn btn-success" @click="sendMessage()"     type="submit">Send</button>
        </div>
    </form>
</template>

<script>

    export default {
        //removed other non-form related stuff
        data() {
            return {
                form: useForm({
                    message: '',
                    conversationID: '',
                    fromID: '',
                    toID: '',
                }),
            }
        },
        methods: {
            sendMessage() {
                console.log(this.form);
            }
        },
    }

</script>

When I hit the enter key, the form gets logged twice, but when I click the send button, the form only gets logged once.

Why does the sendMessage() method get triggered twice when using the @keyup.enter?

0 likes
2 replies
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

The reason why the sendMessage() method is triggered twice when using @keyup.enter is because hitting the enter key triggers the form's default submit behavior in addition to the sendMessage() method. To prevent this, you can add event.preventDefault() to the sendMessage() method to stop the form from submitting twice. Here's an updated version of the code:

<template>
  <form @submit.prevent="submit">
    <div class="input-group">
      <input
        type="text"
        class="form-control type_msg"
        placeholder="Type your message..."
        v-model="form.message"
        @keyup.enter="sendMessage"
      >
      <input type="hidden" v-model="form.conversationID">
      <button class="btn btn-success" @click="sendMessage" type="button">Send</button>
    </div>
  </form>
</template>

<script>
export default {
  data() {
    return {
      form: useForm({
        message: '',
        conversationID: '',
        fromID: '',
        toID: '',
      }),
    }
  },
  methods: {
    sendMessage(event) {
      event.preventDefault()
      console.log(this.form)
    },
  },
}
</script>

Note that we also changed the type="submit" attribute on the send button to type="button", since we're handling the form submission ourselves in the sendMessage() method.

1 like

Please or to participate in this conversation.