Utilizing JavaScript to have the 'enter' key pressed on a specific textbox trigger the same function as the form button

I have a form that consists of a textbox and a functioning submit button which executes a jQuery/AJAX function. I am looking to trigger the same function when the user selects the textbox and presses the 'Enter' key.

I attempted to set up the textbox to initiate the function, but encountered issues where either the text input stopped working entirely or the function was not properly called (e.g., it simply added a parameter to the URL and refreshed the page, rather than executing the intended function). How can I resolve this?

Below is the code for my form:

<form style="border: 1px solid;border-radius:5px;" >
    <div class="input-group mb-2 mr-sm-2 mb-sm-0">
        <input type="text" class="form-control" id="mytextbox" placeholder="ID #" name="parcel">
        <span class="input-group-btn">
            <button class="btn btn-success" id="btnSearch3" type="button" onclick="foo('parcel',document.getElementsByName('parcel')[0].value,'Wizard')">Search</button>
        </span>
    </div>
</form>

Answer №1

To execute JavaScript code after a form is submitted, the onsubmit event can be utilized.

If you wish to prevent the form from submitting in the usual manner, you can incorporate event.PreventDefault.

I have created a fiddle where I assigned an id to the form and implemented an onsubmit function for it. https://jsfiddle.net/qwza104q/.

In cases where both the button and form need to trigger the same function, it is recommended to eliminate the button's onclick attribute and include type="submit" instead.

Answer №2

It's essential to configure the textbox to detect keypress events in order to validate input for ENTER key presses (keyCode 13).

Avoid using inline HTML event handlers (on...) as they:

  • Result in tangled code that is difficult to comprehend and encourages redundancy.
  • Create global anonymous wrapper functions around attribute values, impacting the this binding within the callback.
  • Do not adhere to the W3C Event Handling standards.

Instead, use

object.addEventListener("eventName", callback)
:

// Obtain DOM references:
var btn = document.querySelector("#btnSearch3");
var txt = document.querySelector("#mytextbox");
var parcel = document.getElementsByName('parcel')[0];

// Set up event handlers:
btn.addEventListener("click", doFoo);

txt.addEventListener("keypress", function(evt){
  console.log(evt.keyCode);
  // Validate for the ENTER key
  if(evt.keyCode === 13){
    doFoo();
  }
});

// Common function to be invoked by both handlers:
function doFoo(){
  console.log("Callback called.");
  //foo('parcel', parcel.value, 'Wizard');
}
<form style="border: 1px solid;border-radius:5px;" >
    <div class="input-group mb-2 mr-sm-2 mb-sm-0">
        <input type="text" class="form-control" id="mytextbox" placeholder="ID #" name="parcel">
        <span class="input-group-btn">
            <button class="btn btn-success" id="btnSearch3" type="button">Search</button>
        </span>
    </div>
</form>

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

Having trouble invoking the Carousel function from react-bootstrap

I am currently working on creating a carousel with thumbnails. The goal is to call a carousel function when a user clicks on a thumbnail image. import $ from 'jquery'; import 'react-bootstrap' function changeSlide(){ $('[id^=car ...

Data stored in an array on one screen does not appear on another screen

I am facing an issue in a React project where I have two screens, and on one screen, an array is created and passed as props to the other screen. However, the data from the array is not displaying on the second screen. Here is the relevant code snippet: H ...

Prevent automatic scrolling by clicking when you reach the bottom

In order to replicate the issue I am experiencing, please click on the down button four times, and then click on the up button. You will observe that you need to click the up button one extra time for it to function properly. How can I detect when it has r ...

What is the best method for removing a collection with AngularJS through a RESTful API?

There is a function in my application where users can pick specific entities to delete by selecting checkboxes. The IDs of the selected entities are added to an array. For instance, if I choose the first, second, and fourth entities, their IDs would be: [ ...

What is the best way to delay a method in vue.js?

In the tab element called competences, there is an input field with the reference search. <ul class="nav nav-tabs" id="myTab" role="tablist"> <li class="nav-item"> <a @click="competencesTabClick" aria-controls="Company" aria-sel ...

"Utilizing AngularJS to apply Filter two times within an ng-repeat loop

I recently started learning about angularjs and am currently grasping the concept of filters. However, I have come across an issue where angularjs is calling the filter twice instead of once as expected. I'm quite puzzled by this behavior and unsure w ...

Ways to extract data from form inputs with the help of jQuery

My HTML form allows users to enter data and upon submission, I need to use jQuery to capture the entered values. <form class="my-form needs-validation" method="POST"> <input type="text" id="firstName" name="First Name"> <input type="tex ...

use the abstract function(req, res, next) in a Node environment

Imagine a scenario where I have a route: app.get(abc, (req, res, next) => { if (req.params.ID === undefined) { res.status(400); res.end(); } next(); }); Now, the question arises - would it function in the same way if I w ...

Eliminate the ArrayOfObjects by filtering out the items with a specific ID

Here is an array of objects I've named mycart[]: [{"id":"6","quantity":"20","price":1500,"title":"casual blue strip"}, {"id":"10","quantity":"2","price":1500,"title":"casual blue round neck"},{"id":"5","quantity":20,"price":150,"title":"casual ...

Concern regarding the duration setting in the date-picker

Is there a specific "campaign duration" rule where you must select a date between the first and last day of the month? If you choose a date outside of this range, such as a date from the next month, the Backend API will return an "Input param error." Curr ...

Jumping pages with JavaScript after updating an element through ajax请求

I have a page that fits vertically into the window. When a user clicks on a link, I retrieve another page via ajax and insert it into the required element. Everything is functioning properly, however, when the user clicks on another link, the page jumps up ...

"Adding a delay to each item when using knockout.js to push items into an observable array

I am currently working on an array that populates items into an interface. The issue I am facing is that all the items are appearing at once with a slight opacity animation. What I actually want is for each item to appear individually, with a small delay b ...

I would greatly appreciate your assistance in deciphering the JavaScript code provided in the book "Ajax in Action"

While reading through the Ajax in Action book, I came across a code snippet that has left me with a couple of questions. As someone who is new to web programming and still getting to grips with JavaScript, I am hoping for some clarity on the following: ...

Using JWT for my React-Redux application's server side authentication

As a newcomer to the world of react and redux, I have been searching for answers but all I find is information on server-side rendering. However, that's not what I'm looking for (please correct me if I'm mistaken). What I really need help wi ...

(Discord.JS) Bot failing to send direct message upon user joining the server

When attempting to send a DM message, I am using the following code: bot.on('guildMemberAdd', (member) => { member.send('a'); }); I am experiencing difficulty in understanding why the private message is not being successfully se ...

The functionality of the back button in a JavaScript website only allows users to navigate through their browsing

I'm currently experiencing an issue with the back navigation button on my one-page website. When I load a new page, I use the following code snippet: displayPage = function (page, json) { var stateObj = { "page": page, 'json': j ...

Efficient method for populating a table dynamically with JSON data using JavaScript

While experimenting with jQuery, JSON, and other technologies, I encountered a task where I needed to retrieve table data in JSON format from a loader script on the server and populate my table with it. Currently, I am using code similar to the following s ...

What is the best way to manage a new Error in Node.js while utilizing ES6 Symbols?

In my node.js application, I am implementing an endpoint using ES6 Symbols. Here is an example: // ES6 Symbol Method const taskCreationMethod = { [Symbol.taskMethod]() { return { storeCheckFunc: async function(storeId, employeeId) ...

Comparison of Web Development Techniques: localStorage versus Cached HTTP

Imagine a scenario where there is a web server responding to a GET request by sending a .json file. The response instructs the browser to cache it for a period of 5 years. Furthermore, picture a webpage that initiates this GET request for the JSON data du ...

Avoiding the sudden appearance of unstyled content in Single-File Components

I am looking to update my HTML navigation <div id="header-wrapper"> <div id="header-logo-title"> <nav> <ul id='mainNav'> <li>Home</li> </ul> </nav> ...