Stop the form from submitting when the Enter key is pressed

I am experiencing an issue with my form that contains around 10 input text boxes. When I press the enter key from an input text box, it skips the text boxes in between and goes directly to the submit button. This problem occurs only when using the keyboard as the mouse navigation works fine.

function getElement(elm){
    var elem = document.getElementById(elm);
    return elem;
}


function sendData(){
    getElement('submit-button').addEventListener("click",function(){
        getElement("success-txt").removeClass('display-none');
        if(getElement('pbarcode')){
            var pbarcode = $('#pbarcode').val();
            var pname = $('#pname').val();
            var pprice = $('#pprice').val();
            var poprice = $('#poprice').val();
            $.ajax({
                     url:'getdata.php',
                     method:"post",
                     data:{pbarcode:pbarcode,pname:pname,pprice:pprice,poprice:poprice},
                     cache: false,
                     onSuccess: function(response){
                                alert('success');
                     },
                     onFailure: function(response){
                                alert('failure');
                     }
            });
        }
        else{
           alert("error"); 
        }

    });
}


function showWarnMessage(){
    getElement("submit-button").addEventListener("click",function(){
       alert("you entered submit button");
       var data1 = $('#pbarcode').val();
       var data2 = $('#pname').val();
       var data3 = $('#pprice').val();
       var l3 = data3.length;
       var l1 = data1.length;
       var l2 = data2.length;
       var flag = 0;
       if(l1 < 1){
     
           flag = 1;
       }
       if(l2 < 1){
           flag = 1;
           
       }
       if(l3 < 1){
           flag = 1;
       }
       alert(flag);
       if (flag == '0'){
           alert(flag + "go");
           sendData();
       }
    });
}

showWarnMessage();
ul,li {
list-style : none;
padding :0px;
margin : 0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="create-user" method="post">
                            <ul id="create-new-user-page">
                                <li>
                                    <span>Product Barcode</span>
                                    <input type="number" id="pbarcode" name="barcode" class="form-data" required>
                                </li>
                                <li>
                                    <span>Product Name</span>
                                    <input type="text" class="form-data" name="pname" id="pname" required>
                                </li>
                                <li>
                                    <span>Product Price</span>
                                    <input type="number" class="form-data" name="pprice" id="pprice" required>
                                  
                                </li>
                               
                                <li>
                                    <input type="submit" id="submit-button"  Value="Submit" name="submit_data">
                                </li>
                
                            </ul>
                            
                        </form>

I have attempted to use event.preventDefault(); on 'enter' click on text boxes in order to address this issue. Here are the codes:

event.preventDefault();

function preventDefault(elem){
   getElement('elem').addEventListener('keypress',function(){
       if (event.keyCode == 13) {
            event.preventDefault();
            alert('calling ')
       }
   }); 
}
preventDefault('pname');
preventDefault('pprice');
preventDefault('pname');
preventDefault('pbarcode');

However, this approach also yields the same result. I am looking for a solution that allows the form to work seamlessly with the enter key, moving from one input text box to another instead of going straight to the submit button.

Answer №1

<input type="button" id="submit-button" Value="Submit" name="submit_data">

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

The data in my JSON string is not fully received through the HTTP GET request

Whenever I send my array to the PHP file, it receives incomplete data. The content of my 'arr' variable is as follows: [["╪▒┘à┘╛┘╪د","67126881188552864","Empty,Empty,Empty,Empty,8644,-360,-4,8691,-3.48,-313,1015,4.334 M,1392/12/2 ...

Ways to link a Javascript or Jquery function to an HTML form

I am looking to develop a form that can extract email addresses from input text. While I know there are many scripts available that can do this quite easily, my goal is to create one on my own. After reading, researching, and experimenting with differ ...

Vim: Turn off autocomplete when using insert mode key bindings

I've set up a mapping in insert mode to automatically indent brackets: inoremap [;<CR> [<CR>];<Esc>O<Tab> When I use it, the result looks like this (the pipe character represents the cursor): const a = [ | ]; Now, I want ...

Accessing the req object in Node.js using Express

Currently, I am attempting to redefine the function send in order to include an express-session value with each response. Unfortunately, I seem to be encountering issues accessing the variable req within the definition of send. 01| let app = express(); 02| ...

Tips for preventing recursion when utilizing scrollIntoView() in a scroll event handler

My goal is to break down my website into screen-sized sections that automatically scroll to the next section when a user begins scrolling. I attempted to accomplish this by using the following code: $(window).scroll(function() { getElementToScroll().s ...

Utilizing ES6 promises in node.js to send a null response

I'm looking for assistance on how to execute a query using ES6 native promises in node.js. The code I have below is what I've been working with: let arr= []; conn.query('select * from table1', (err, b) => { for (let i = 0; i ...

Increase a variable within a looping structure using jQuery

I am faced with a task that involves selecting two values from different dropdown lists, such as 1001 from the first dropdown and 1003 from the second. Upon clicking the 'add' button, I need to pass these selected values, along with the values in ...

retrieve a string from a given array

I need to retrieve a string from an array in vue and display it on the screen. Here is the method I created for this purpose: displayFixturesName() { const result = this.selectedFixture.toString(); document.getElementById(& ...

What are the steps to effectively populate a mongoose schema?

In my application, I have a model for people: const mongoose = require('mongoose'); const Schema = mongoose.Schema; const PersonSchema = new Schema({ name: String, cars: [{ type: Schema.types.ObjectId, ref: 'Cars' }] }); ...

The preflight OPTIONS request for an AJAX GET from S3 using CORS fails with a 403 error

I have come across various discussions and issues related to this topic, but unfortunately, I have not been able to find a solution yet. I am attempting to use AJAX GET to retrieve a file from S3. My bucket is configured for CORS: <?xml version="1.0" e ...

Looking for an Effortless Loading jQuery Image Slider or: Unleashing the Power of cross-slide

I am in need of assistance with implementing lazy loading for images in a jQuery slideshow that pulls from Flickr. Although everything is running smoothly, I would like to optimize the image loading process by only loading them on demand. Currently, I am ...

Create a React component using the value stored within an object

I am interested in creating an object: import React from "react"; import { Registration } from "../../"; const RouteObj = { Registration: { route: "/registration", comp: <Registration /> } }; export default RouteObj; Next, in a separat ...

The function iframe.scrollTo() is not effective for scrolling through Excel or PowerPoint documents on an iPad

I am trying to create a custom scrolling feature for iframe content specifically for iPad. Currently, I have set up my iframe like this: <div id="scroller" style="height: 300px; width: 100%; overflow: auto;"> <iframe height="100%" id="iframe" ...

Guidelines for utilizing a loader to handle a TypeScript-based npm module

I am currently facing a challenge with my React and JavaScript project as I attempt to integrate an npm module developed with TypeScript. The issue lies in configuring my project to compile the TypeScript code from this module, resulting in the error messa ...

Exploring the integration of AJAX callbacks with ASP.NET User controls

What is the most effective approach for integrating user controls that require AJAX callbacks? My objectives include: Utilizing browser events (such as drag and drop) to trigger an AJAX notification that can initiate a control event, allowing the code o ...

React is struggling to locate the specified module

Once I've set up my react project using npx create-react-app called my-app, I proceed to run npm start only to encounter the error shown in the image below. Running node version: 12.16.1 with npm version: 6.13.4 View the error message her ...

Is it possible to share a Vue.js component by "transferring" it rather than duplicating it?

In my comment system project using Vue.js, I have over 300 comments to manage. Each comment has an admin section that appears when the cursor hovers over it. Duplicating the admin section component for each comment is not ideal as it creates unnecessary l ...

Notifying users with a beeping sound in PHP through AJAX queueing

I am currently developing a Queuing system for my helpdesk support platform. I am facing an issue with detecting changes in the input value. I want to trigger the play_sound() function every time the input value increases. The current value of the input is ...

Troubleshooting Problem with Angular JS Ng-Repeat

I have a specific situation where I want to showcase the elements that exist in only one array. If an element is also present in another array, there is no need to display it. My HTML structure looks like this: <div ng-repeat="array1Value in array1"&g ...

Passing the index in React Native

I am currently developing a music app utilizing the react-native-track-player library. I have created three components named Clusters, Songlist, and Play. Understanding How the Screen Works The flow of components is as follows: Clusters component -> S ...