Unexpected button behavior sparked by Vue.js

Check out this fiddle I created: https://jsfiddle.net/frvuw35k/

<div id="app">
  <h2>Vue Event Test</h2>
  <form @submit.prevent>
    <div class="form-group row">
            <div class="col-sm-12 input-group">
                <input v-model="search" class="form-control" placeholder="Search users by Display Name"
                            @keyup.enter="doSearch">
                <div class="input-group-append">
                    <button class="btn btn-primary" :disabled="!search" type="button"
                                @click.prevent="doSearch">
                            Search
                    </button>
                </div>
            </div>
        </div>
    <div class="form-group row">
                <div class="col-12">
                    <button v-if="showButton" class="btn btn-info"
            @click.prevent="doSthElse">Do something else</button>
                </div>
            </div>
  </form>
</div>
new Vue({
  el: "#app",
  data: {
    search: null,
    showButton: false
  },
  methods: {
    doSearch: function(){
        console.log('do search:', this.search)
      this.showButton = true
    },
    doSthElse: function(){
        console.log('do something else')
    }
  }
})

This scenario mirrors a situation I encountered in my Vue application.

In this case, a second button only appears when a specific condition is met. This condition is triggered by hitting the enter key in the input field.

Strangely, after the condition is met and the second button is shown, hitting enter again or clicking elsewhere and returning focus to the input triggers the second button...

I'm yet to determine the cause of this and how to prevent it.

Answer №1

Solution Explanation

The issue stems from the default behavior of browsers in a form.

Typically, pressing the Enter key when focused on an input would submit the form.

When submitting a form, the browser looks for a button within the form to trigger the action, such as your "Do something else" button in this scenario.

Therefore, pressing Enter would inadvertently activate the last button, invoking the doSthElse method.

Resolution Steps

To resolve this issue, you can add a @keydown.enter.prevent listener to the form to prevent the default behavior from occurring.

I have implemented the fix in your code on this updated fiddle: https://jsfiddle.net/vy57d63f/

Answer №2

Here's a helpful tip: Utilize the @keydown event handler with the prevent modifier.

<input v-model="search" class="form-control" placeholder="Search users by Display Name"
                        @keydown.enter.prevent="doSearch"/>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Testing an ExpressJS route and their corresponding controller individually: a step-by-step guide

I have set up an Express route in my application using the following code snippet (where app represents my Express app): module.exports = function(app) { var controller = require('../../app/controllers/experiment-schema'); app.route('/a ...

What is the most efficient way to handle dependencies and instantiate objects just once in JavaScript?

I am interested in discovering reliable and tested design patterns in Javascript that ensure the loading of dependencies only once, as well as instantiating an object only once within the DOM. Specifically, I have the following scenario: // Block A in th ...

Struggling with a peer requirement for grunt@~0.4.0 during the installation of grunt plugins? Here's how to resolve

I recently tried to set up some Grunt plugins such as grunt-contrib-clean and grunt-contrib-watch using the commands npm install grunt-contrib-clean --save-dev and npm install grunt-contrib-watch --save-dev However, I encountered the following warnings: n ...

Error: The property 'rtl' is not defined and cannot be read

I'm currently in the process of developing a vuejs component library that utilizes vuetify 2.1.4 and attempting to import it into another application locally through npm link. However, I'm encountering numerous errors such as TypeError: Cannot ...

Looping through an array of nested objects using Vue

I have encountered a challenge with accessing specific data within an array that I am iterating over. The array is structured as follows, using Vue.js: companies: [ name: "company1" id: 1 type: "finance" additionalData: "{& ...

What is the most secure approach for defining the file path of an HTML file within an express.js application?

In my directory setup, I have the index.js file located at: path/to/home-page/src/routes This is also where you can find the __dirname. The html file resides at: path/to/home-page/public/bootstrap/Homepage/page.html To serve the html document by relati ...

Is there a way to send an array of objects as parameters in JavaScript?

I have an array of objects with the same key name. My goal is to pass each address key inside those objects as a parameter to my API. How can I achieve this? The response I receive looks something like this: { '0': { address: 'abcd' }, ...

I am having trouble with my jQuery login function not properly connecting to the PHP file

Hey there, I've been working on creating a login system from scratch by following an online tutorial. The initial Javascript is functioning properly as it detects errors when the inputs are empty. However, once I enter text into the input fields and c ...

Utilizing FabricJS to create a canvas with synchronized scrolling to the window

In the process of developing an app, I am utilizing the Html2canvas library to capture a screenshot of the body. Once the screenshot is taken, it is displayed in a canvas component using the fabricJS framework. The canvas is set to have the same height and ...

A guide on combining two native Record types in TypeScript

Is it possible to combine two predefined Record types in TypeScript? Consider the two Records below: var dictionary1 : Record<string, string []> ={ 'fruits' : ['apple','banana', 'cherry'], 'vegeta ...

The hierarchy of CSS in Vue components

I've developed a customized CSS framework to streamline the design process across all my internal projects. The central file is structured as shown below: @import "~normalize.css/normalize.css"; @import "_variables.scss"; @import "_mixins.scss" ...

What factors determine how a React component should be re-rendered based on a specific file?

I am facing a challenge with a file that stores an array of objects. There is a component responsible for fetching data from this file and rendering the list. The issue arises when the file gets updated externally, as I need the component to reflect these ...

Utilize AJAX to accurately capture and handle error codes

Here is a snippet of code that I want to send to my server: $.ajax({ type: 'POST', url: 'post.php', data: { token: '123456', title: 'some title', url: 'http://somedomain.com', data: & ...

Utilize a jest mock object and pass it as a method parameter to achieve seamless testing

I am attempting to create a mock object (ColumnApi from ag-grid) using jest and then pass it as a parameter to a function that calls the "getAllColumns" method from ColumnApi. I am not concerned with how the "getAllColumns" method functions, but I want it ...

Building a NodeJS powered single page application that consumes API data

Currently, I am working on developing a single-page JavaScript web application that will periodically fetch data from multiple public and possibly private APIs. The objective is to display and update this data in various tables. I could opt for creating th ...

Enhance a DOM element using personalized functions in jQuery

Seeking advice on how to create custom widget placeholders with a "setvalue" function specific to each type of widget: $.fn.extend($(".dial"), { setval: function(val) { }); Attempting to avoid extending jQuery.fn directly since different widget type ...

Is it possible to include a visible comment in an ajax call that can be viewed in Fiddler when analyzing the outgoing data?

Here is an example of the code I am working with: $.ajax({ cache: false, url: "/xx" }).done(onAjaxDone).fail(function (jqXHR, textStatus, errorThrown) { Dialog.Alerts.ajaxOnFailure(jqXHR, textStatus, err ...

Execute a command and direct the input/output to designated files

My goal is to execute a child process in the background while also modifying its output (like adding timestamps) and directing it to specific files. Currently, I am approaching this task as follows: try { var out = fs.createWriteStream(`${this.logdir}/$ ...

Adjust the CSS for the "a" tag's "title" attribute

I am using jquery.fancybox to create an image modal on my website. I have noticed that I can add a description using the title attribute. However, when the description is too long, the text is displayed on a single line and some of it disappears. How can ...

Is there a way to utilize ajax to submit a form and upload a file to a spring controller?

I have a form with four fields: file, name, type (as a string), and taskInstanceId. <form> <table id="documentDetailsTable"> <tr> <td>Document Type: </td> <td><select id="documentType" ...