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

Exiting a void method in JavaScript/Typescript using the return or break statement

I find myself dealing with a complex method in Typescript that contains multiple if else if else constructs. It's a void method, and I'm wondering how I can exit the method based on a specific if condition without having to execute the remaining ...

Using Vue's mdi icons within a string

What is the best way to incorporate mdi icons into a string and have it rendered as an icon within a method that acts as a component in a cell of an ag-grid table? import { mdiPencil } from "@mdi/js"; data(){ return{ mdiPencil } } methods ...

Tips for implementing a single function across multiple HTML classes using JavaScript

For the past few days, I've been struggling with a JavaScript issue as a newcomer to the language. $(document).on('click', '.content-click', function(){ $(".content-click span").toggleClass("clicked"), $(".content-view") ...

The Angular $http.jsonp() function can only be executed one time

Upon the first response being successful (alert->done), any subsequent hits will result in an 'error' response. I attempted to resolve this issue by adding some config parameters with 'cache: false', but it still only works the first t ...

Assign the array value to all inputs that share the same class tag

Does anyone know how to iterate through all tags with the same className and retrieve their values? var quantities = []; $(".add_more_items").each(function(){ quantities.push($(this).val()); }); Here is an example of the result: ['1&apo ...

Step-by-step guide on incorporating a hyperlink within a row using @material-ui/data-grid

I am currently using @material-ui/data-grid to showcase some data on my webpage. Each row in the grid must have a link that leads to the next page when clicked. I have all the necessary data ready to be passed, however, I am facing difficulty in creating a ...

Integrate your React Native application with a Node.js backend on your local machine

My attempt to establish a connection between my react native app and my node.js app on a Windows system has hit a roadblock. While I am able to receive responses from the node API using Postman, the response from the react native app is coming back as unde ...

Encountering the issue of receiving an undefined value for a variable despite having previously defined it within

I’ve been working on implementing the Google Maps distance matrix API with the google-distance-matrix library. Here’s the code snippet I’m using: app.get("/users", (req, res) => { // console.log(req.query); // res.send(req.query); ...

Error in Discord Bot: discord.js showing TypeError when trying to read the length of an undefined property

I'm currently working on developing a Discord bot and using CodeLyon's Permissions V2 video as a guide for reference. There seems to be an issue in my message.js file which contains the following code: require('dotenv').config(); //cre ...

JavaScript math validations not functioning correctly

This new project I've been working on involves presenting a multiplication problem and notifying the user if their answer is correct through an alert. The issue arises when the program incorrectly verifies the answers. Take a look at the code: < ...

Using Jquery to set values for css properties

I've recently started using jquery and I have a task related to a drop-down menu that I'm struggling with: if (scrnwidth <= 761) { if (display was block) { //Defaultly testi has display:none property. testi = m ...

How can I implement a for loop in Node.js?

I am currently experiencing an issue with my for loop while attempting to retrieve data from MongoDB and display it in the browser. The problem is that it only iterates through once, resulting in only the first entry being output. Strangely enough, when ...

Transforming a JavaScript chained setter into TypeScript

I have been utilizing this idiom in JavaScript to facilitate the creation of chained setters. function bar() { let p = 0; function f() { } f.prop = function(d) { return !arguments.length ? p : (p = d, f); } return f; } ...

Expanding Vendor Class in Laravel

Currently, I am utilizing a cart system (\Gloudemans\Shoppingcart) but I am looking to customize the default total() method: namespace Gloudemans\Shoppingcart; /** * Obtain the overall total price of the items in the shopping cart. ...

Paper.js: Is there a way to prevent canvas height and width from changing when the window is resized?

My canvas with paperjs is set up to resize dynamically when the window is resized. I appreciate any help in advance. HTML <canvas id="myCanvas" height="800" width="1000"></canvas> JS var Initialize = function () { var canvas = document ...

Troubleshooting: Issue with Updating Views in Angular JS

I've been attempting to change the view from the controller, but it's just not working properly. app.js var app = angular.module('vla', ['ngRoute']); app.config(function ($routeProvider){ $routeProvider ...

Encountering a PHP error in Laravel Vapor when attempting to upload a file from the front-end

Oops! Some key environment variables are missing: AWS_BUCKET, AWS_DEFAULT_REGION, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY I am utilizing the Laravel Vapor library to handle file uploads from the front-end due to large file sizes (6.8mb). Below is my cod ...

I am looking to have the first option in the dropdown menu appear as a placeholder text

In my form, I have two phone number fields - one for mobile phone and the other for home phone. I need to make only one of them mandatory. Can someone please advise me on how to accomplish this? ...

Retrieve the user ID during the login process using LoginController.php in Laravel

After a user logs in, I need to retrieve their user ID immediately. I have attempted to do this using a request but encountered an error message that says: "Too few arguments to function App\Http\Controllers\Auth\LoginController::red ...

How to make Sails.js package accessible across all modules

Recently, I have been using Sails frequently and came across a common practice question. Whenever I need to use a specific NPM package multiple times in a project, I typically include it in my config/bootstrap.js file like this: module.exports.bootstrap = ...