How to Stop Form from Automatically Submitting in Laravel 5.5 and vue-typeahead's onHit method

I have integrated the vue-typeahead component into my Laravel project using vue-typeahead.

However, I am facing an issue where when I select an entry from the result list by pressing the "enter" key, the form automatically submits. Is there a way to prevent this behavior in the onHit method?

Below is the code snippet of my component:

    import VueTypeahead from 'vue-typeahead';
    import Axios from 'axios';
    Vue.prototype.$http = Axios;

    var elem;

    export default {
        extends: VueTypeahead,
        props: ['targetInput', 'keywordCategory', 'append'],

        data () {
            return {
                src: '/api/autocomplete',
                data: {
                    query: this.query,
                    category: this.keywordCategory,
                    append: this.append
                },
                limit: 10,
                minChars: 3,
                selectFirst: true,
                queryParamName: 'search'
            }
        },

        methods: {
            onHit (item) {
                elem = document.getElementById(this.targetInput);
                if(this.append !== undefined && elem.value !== '') {
                    elem.value += this.append + item.name;
                } else {
                    elem.value = item.name;
                }
            }
        }
    }

Answer №1

Your current code most likely resembles the following:

<form>
    <input type="text">
</form>

To prevent form submission when pressing enter, you can handle the submit event like this:

<form  @keypress.enter="$event.preventDefault()">
    <input type="text">
</form>

The @keypress.enter is used to trigger a function when the user presses the enter key on an input element within the form.

By using $event.preventDefault(), you are disabling the default action of submitting the form in this scenario.

In this case, there is no need to modify onHit.


(Update) If you want to achieve the same result without modifying the form element, you can add a Vanilla JS event listener for the form within Vue's mounted function.

For example:

<script>
    export default {
    ...
    mounted() {
        document.querySelector('#test-form').addEventListener('keypress', function (e) {
            var key = e.which || e.keyCode;
            if (key === 13) { // 13 represents the enter key
                // Code to execute on enter press
                e.preventDefault();
            }
        });
    }
}

</script>

For an example, refer to the ./components/Hello.vue file in https://codesandbox.io/s/720zzmj7z1.

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

jQuery Autocomplete - Showing array of options upon selecting input field in Internet Explorer

After encountering an issue with the autocomplete feature in a web application, I posted a question on Stack Overflow. The provided answer solved the problem in Chrome, but unfortunately, it did not work in Internet Explorer 8 or 9, and possibly earlier ve ...

Encountered an issue while compiling code using the Istanbul plugin

I'm currently working on generating a code coverage report for my ReactJS project using the babel-istanbul-plugin. However, when I incorporate "istanbul" as a plugin in my .babelrc file and attempt to build, I encounter the following error: ERROR in ...

Limit users to entering either numbers or letters in the input field

How can I enforce a specific sequence for user input, restricting the first two characters to alphabets, the next two to numbers, the following two to characters, and the last four to numbers? I need to maintain the correct format of an Indian vehicle regi ...

detecting key presses on documents using javascript

I'm having trouble capturing document-level key press events on a webpage. I've tried using the following code: $(document).bind('keydown', 'a', keyevent_cb); It works fine in IE, but it's not consistent in Firefox. I&a ...

How to efficiently manage drop-down menus on a website using VBA specifically designed for Internet Explorer

I am a beginner in VBA and coding, seeking assistance from the community. The purpose of this VBA code is to automate the following steps: Open Internet Explorer Enter user ID and password to login Select the current date Select a specific option (X1) fr ...

Send the Vue component as an argument to the function

Currently, I am in the process of transferring a project to Vue and utilizing Muuri as a layout manager. In my code, I have the following snippet: grid.add(itemElem, { layout: false, active: false }); The variable itemElem used to be an HTML element c ...

Transfer a file from the file:///var/mobile/Applications/ directory to an accessible location for reading in Cordova/PhoneGap

I have a unique 'whitelabel' app that customizes itself for each client by downloading image files from a configuration server. However, I am facing an issue where the images are not displayed and instead showing a "Not allowed to load local reso ...

Activating a function that requires locating a dynamically loaded element on the webpage using AJAX

I have a unique page on my website that allows users to make edits. Whenever they click on an item, the edit form is seamlessly loaded into a specialized section of the page using AJAX. Depending on the chosen item, the form fields are already prefilled w ...

Merging Documents in PouchDB

I need to retrieve equipment data from pouchdb/couchbase that has users assigned to them. Each piece of equipment has an _id and a checkedOutBy field with the user._id as its value. The employee object contains the user's name. How can I retrieve the ...

The issue persists with UIkit modal element remaining in the DOM even after the parent component in Vue.js is destroyed

In my Vue app, I am utilizing the UIKit modal. UIkit.modal(element).show(); // This adds the class uk-open and sets style to display:block UIkit.modal(element).hide(); When I hide the modal, it simply removes the class uk-open and the inline style of dis ...

Restricting the Vue for-loop results to display only the current item in use

Currently, I am utilizing a for-loop to retrieve all of my posts, followed by employing a partial to obtain a list of all the usersThatUpvoted on that post. <div v-for="p in posts" style="padding: 16px"> <div> &l ...

Loop through a non-array or non-object / handling both arrays and non-arrays equally

Sometimes, I find myself needing to handle arrays and single objects in a similar manner. For instance, I may have an object property that can be either an array or just a string (like the scale property): [ { "name": "Experiment type14", "id": ...

Clickable Angular Material card

I am looking to make a mat-card component clickable by adding a routerlink. Here is my current component structure: <mat-card class="card" > <mat-card-content> <mat-card-title> {{title}}</mat-card-title> &l ...

What steps can be taken to ensure that a dropdown menu responds instantly to the JavaScript code provided?

Upon discovering this code snippet in a different answer (on jsfiddle), I noticed that it allows for the appearance of a text box when the user selects 'other' from the dropdown menu. However, when I include '<option value='0' s ...

Angular JS is failing to update views when passing dynamic IDs

I have implemented a method in my controller where I pass a dynamic id using the ng-init function, fetch a response through ajax calls, and try to print the response. However, I am facing an issue as the response is not getting printed. I am using ng-repea ...

Unable to specify a particular <div> for fetching data using jQuery AJAX in ASP.NET

While working on the following Javascript code, I encountered an issue where the text specified inside the CommentItem div I am appending is not displaying. However, my main concern revolves around targeting ContainerPh which is located above the txtCommen ...

Tips for utilizing CDN in vue cli?

My experience with packing frontend projects is limited. In the past, I only used JQuery for frontend development. Now, I have a project created by vue-cli and packed by webpack. I would like to load libraries from remote CDNs instead of my local server. ...

Imitating the Frameset Separator's Actions

The latest HTML5 specification has eliminated the <frameset> element. One useful feature of the <frameset> tag that is hard to replicate without it is: In a frameset, you can adjust the position of the frame divider line with the mouse. Is t ...

Using PHP and JavaScript to enhance functionality around a hyperlink

I am trying to incorporate a small piece of Javascript on my website to ensure user confirmation. While I have successfully used the 'onclick' function with buttons, I am facing difficulty implementing it on a link. Here is the link in question: ...

When conducting tests using Selenium and the headless Google Chrome browser in Java, the dynamic JS content fails to load

Currently, I am in the process of testing a website that I have developed as part of a Spring Boot project using Selenium. While I can successfully test basic functionalities such as page loading and title verification, I am encountering difficulties when ...