Discrepancy between keydown event and button click functionality

Whenever I click the search button, the sendTitle() function executes flawlessly. However, when I press the enter key (keyCode == 13), the sendTitle() function consistently throws a catch error response (alert cannot connect). I am curious if anyone understands why it fails to work when I hit enter on the form input field. You can find my code in a jsFiddle here. Thank you!

https://jsfiddle.net/k_g_j/yzcomd7s/4/


        var sendTitle = function() {
            // Function logic here
        }
    

        body {
          font: 400 15px Lato, sans-serif;
          /* More styles here */
        }
    

        <!DOCTYPE html>
        <html lang="en">
            <head>
                <!-- Head Content Here -->
            </head>
            <body>
                <!-- Body Content Here -->
            </body>
        </html>
    

Answer №1

For a quick solution:

Remember to use e.preventDefault() instead of just e.preventDefault

Also, ensure that it is placed within an if statement like the following:

if (e.keyCode == 13) {
  e.preventDefault();
  sendTitle();
}

Live Demonstration

var sendTitle = function() {
  var title = $("input[name='movie-search-title']").val();
  console.log(title)
  getMovie(title)
  getQuotes(title)
}
$("input[name='movie-search-title']").keydown(function(e) {
  if (e.keyCode == 13) {
    e.preventDefault();
    sendTitle();
  }
})
// Movie Search 
var getMovie = function(title) {
  // Code for fetching movie details
};
var getQuotes = function(title) {
  // Code for fetching quotes related to the movie
};

// Additional functions for displaying movie and quotes 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

What steps can I take to fix the sum function?

My function calculates heart rate targets for sports, but there seems to be an issue in the switch statement. The final sum in the function is not being computed properly. For example, if someone is 20 years old with a resting heart rate of 50 beats per mi ...

Using JQuery to trigger CSS3 animations on one element when clicking on another

My Rails app has a feature similar to reddit where users can upvote or downvote content. I'm currently working on creating a CSS3 animation that triggers when a user clicks the downvote button. Here's how I'm using JQuery: <div class="a ...

Plugin that collapses dropdown menus when the mouse hovers over them, powered by jQuery

My webpage has a simple set of links, and one of them triggers a dropdown menu to appear on mouseover (refer to the image below). The dropdown submenu becomes visible when the link "How fast is it?" is hovered over, and remains fixed in place due to the di ...

Why do all the values in my table turn into input boxes when I click the edit button?

When working with my HTML, I am using ngFor to iterate through a list of items and display them in a table. However, when I try to edit an item by clicking on it, the input box opens but all the table rows display the same value. <tr *ngFor="let item o ...

Looking to refine your search in materialize css/bootstrap when utilizing cards?

I recently embarked on a project to create an HTML page utilizing Materialize CSS and Bootstrap. My goal was to incorporate cards representing YouTube videos, along with a search bar that could filter through the cards and display the relevant one. However ...

The toLowerCase method seems to be malfunctioning along with several other functions

JS var score = 0 var yes = "yes" var pokemonName = []; var bg = []; var index = 0; document.getElementById('repete').style.visibility = 'hidden'; (function asyncLoop() { background = bg[num = Math.floor(Math.random() ...

Error encountered in React and Redux: Unable to read properties of undefined (specifically 'region')

Whenever a user clicks on edit, I am fetching data (an object) into a redux state and displaying it in a textarea. Here is the code snippet: const regionData = useSelector((state) => state.myReducer.userDetailList.region); The problem arises when this ...

Using the Sequelize query string prefix to find data that starts with a specific value

I'm currently working on an autofill feature that takes a string input and provides a list of string suggestions. While using Sequelize's iLike:query, it retrieves all strings in which the queried string is present. However, my goal is to priori ...

Ever since I upgraded my three.js, my code seems to have lost its functionality

I encountered an issue while transitioning from three.js version r58 to r73. The code that previously displayed the model perfectly is now failing to render the model. Despite detecting the mesh in the debug window, the model remains invisible on the scree ...

Are brackets or parentheses allowed in URLs?

When generating URLs for my AdWord campaigns, I have noticed that some campaign names contain brackets such as ( ) and [ ]. A sample URL that I have generated looks like the following: http://www.website.com/?utm_source=google%5BB%2B%5D&utm_medium=cp ...

"Step-by-step guide to updating user information in MongoDB with the help of node.js

I have been working on a basic express app with MongoDB integration, allowing users to register, log in, and log out successfully. However, I am facing an issue when attempting to implement the functionality to edit user data. The code runs without any err ...

Retrieve data using a jQuery select query

Is there a way to use a jquery select function to retrieve the email from a users array that contains additional data for each user? var _userObject = linq.From($vw.listVwObservable().Users()); After executing this code, I get an Array[6] where each ele ...

Effective strategies for minimizing the bundle size of your NextJs application

Recently, I launched my first NextJS app and was surprised to see that the initial bundle size is around 1.5Mb, which seems quite large for me as a beginner in using Nextjs. I have shared an image of the yarn build and also my package.json. All the pages ...

What is the best way to retrieve and display data from a JSON object that has been encoded using json_encode on one page.php, in another page.php?

I have a specific requirement that involves calling JSON data from one PHP page and displaying it on another PHP page. Can someone guide me on how to achieve this? Below is the JSON code that I need to retrieve: <?php include("Connect.php"); $Db = m ...

Step-by-step guide on interacting with a JavaScript menu: Click to open the menu and close it by moving

My menu JavaScript function now opens with a click and closes with a click. I want it to open with a click and close when the mouse leaves the button. $("#theme_select").click(function() { if (theme_list_open == true) { $(".center ul li ul").h ...

Querying a Database to Toggle a Boolean Value with Jquery, Ajax, and Laravel 5.4

I am facing an issue with a button I created to approve a row in a table. It seems that everything is working fine when clicking the button, but there is no change happening in the MySQL database Boolean column. Here is the code for my button: <td> ...

How do I limit search bar queries to only display results from my website and provide suggestions?

Is there a way to customize the search bar on my website so that it only finds results within my pages and also provides suggestions? ...

Angular 2: Harnessing the power of Observables with multiple Events or Event Handlers

In the component template, I have grouped multiple Inputs and their events like this: <tr (input)="onSearchObjectChange($event)"> <th><input [(ngModel)]="searchObject.prop1"></th> <th><input [(ngModel)]="searchObje ...

Encountering a CORS issue when utilizing Stripe with various servers while navigating with a Router

I have a router that utilizes Router.express(). The backend operates on port 5000, while the frontend runs on port 3000. Within the frontend folder, there is a button with a fetch request (http://localhost:5000/create-checkout-session). In the backend, the ...

What is the purpose of the code snippet 'jQuery.each(lines, function(lineNo, line)'?

As a newbie to jquery and ajax, I stumbled upon some code online that caught my attention. The code snippet below prompted me to question its purpose and functionality: lines = newLine.split('#'); jQuery.each(lines, function(lineNo, line) ...