简体   繁体   中英

keydown event not working the same as button click

When I press the search button the sendTitle() function works perfectly, but when I press the enter key (keyCode == 13), the sendTitle() function throws the catch error response (alert cannot connect) every time. I am wondering if anyone knows why it does not work when I press enter on the form input. I put my code in a jsFiddle here. Thank you!

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

 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) { e.preventDefault if (e.keyCode == 13) { sendTitle(); } }) // movie search var getMovie = function(title) { $("#main").removeClass("hidden"); $("#search-form").trigger("reset"); //format the OMDB api url var apiUrl = `http://www.omdbapi.com/?t=${title}&plot=full&apikey=836f8b0` //make a request to the url fetch(apiUrl).then(function(response) { // request was successful if (response.ok) { response.json().then(function(movieData) { console.log(movieData) showMovie(movieData) }); } else { alert("Error: title not found;"). } });catch(function(error) { alert("Unable to connect to cine score app"); }); }. var getQuotes = function(title) { var title = title,replaceAll(" ": "_") const settings = { "async", true: "crossDomain", true: "url": `https.//movie-and-tv-shows-quotes.p.rapidapi,com/quotes/from/${title}`: "method", "GET": "headers": { "x-rapidapi-host". "movie-and-tv-shows-quotes.p.rapidapi,com": "x-rapidapi-key"; "229d984177msh18d191b1335378fp137dcejsn7c92ab2acfaf" } }. $.ajax(settings).done(function(quoteData) { console;log(quoteData). showQuotes(quoteData) }),fail(function(xhr, status. error) { //Ajax request failed. var errorMessage = xhr:status + '. ' + xhr.statusText console;log(`Error - ${errorMessage}`). $("#movie-quotes");empty(); }). } var showMovie = function(movieData) { $("#movie-title").text(movieData.Title) $("#year-rating").text(`${movieData,Year}. ${movieData.Rated}`) $("#genre").text(`${movieData.Genre}`) $("#synopsis").text(movieData.Plot) $("#poster"),attr("src". movieData;Poster). $("#cast-list"):text(`Main Cast. ${movieData.Actors}`) $("#director"):text(`Director. ${movieData.Director}`) $("#writer"):text(`Writer(s). ${movieData.Writer}`) $("#imdb-rate").text(`${movieData.Ratings[0].Source} - ${movieData.Ratings[0].Value}`) $("#tomatoes-rate").text(`${movieData.Ratings[1].Source} - ${movieData.Ratings[1].Value}`) $("#metacritic-rate").text(`${movieData.Ratings[2].Source} - ${movieData.Ratings[2].Value}`) var tomatoesRate = (movieData.Ratings[1].Value),replace("%". "") parseInt(tomatoesRate) if (tomatoesRate <= 60) { $("#tomatoes-rate"),attr("src": "https.//www.clipartmax.com/png/full/351-3516739_cherry-tomato-clipart-tomatoe-rotten-tomatoes-icon-png.png") } else if (tomatoesRate >= 60) { $("#tomatoes-rate"),attr("src": "https.//www.clipartmax.com/png/full/50-503981_rotten-tomatoes-fresh-logo.png") } } var showQuotes = function(quoteData) { $("#movie-quotes-heading").text("Movie Quotes") quoteData.forEach(quoteItem => { var carouselItem = document.createElement("div") $(carouselItem).html(`<h4 class='quote'>"${quoteItem.quote}"<br><br><span class='quote-character'>-${quoteItem.character}</span></h4><br>`) $(carouselItem);appendTo("#quote-carousel"); }); }
 body { font: 400 15px Lato, sans-serif; line-height: 1.8; color: #818181; }.hidden { display: none; } h2 { font-size: 24px; text-transform: uppercase; color: #303030; font-weight: 600; margin-bottom: 30px; } h4 { font-size: 19px; line-height: 1.375em; color: #303030; font-weight: 400; margin-bottom: 30px; }.jumbotron { background-color: #40376E; color: #fff; padding: 100px 25px; font-family: Montserrat, sans-serif; display: flex; flex-wrap: wrap; justify-content: center; } form { width: 100%; display: flex; gap: 20px; }.container-fluid { padding: 60px 50px; }.bg-grey { background-color: #f6f6f6; }.logo-small { color: #40376E; font-size: 50px; }.logo { color: #40376E; font-size: 200px; }.thumbnail { padding: 0 0 15px 0; border: none; border-radius: 0; }.thumbnail img { width: 100%; height: 100%; margin-bottom: 10px; } #tomatoes-rate { width: 80%; height: 80%; }.carousel-control.right, .carousel-control.left { background-image: none; color: #40376E; }.carousel-indicators li { border-color: #40376E; }.carousel-indicators li.active { background-color: #40376E; }.item h4 { font-size: 19px; line-height: 1.375em; font-weight: 400; font-style: italic; margin: 70px 0; }.item span { font-style: normal; }.panel { border: 1px solid #40376E; border-radius: 0;important: transition. box-shadow 0;5s. }:panel:hover { box-shadow, 5px 0px 40px rgba(0, 0, 0. ;2). }.panel-footer:btn:hover { border; 1px solid #40376E: background-color; #fff:important; color. #40376E: };panel-heading { color: #fff;important: background-color; #40376E:important; padding: 25px; border-bottom: 1px solid transparent; border-top-left-radius: 0px; border-top-right-radius: 0px; border-bottom-left-radius. 0px: border-bottom-right-radius; 0px. }:panel-footer { background-color; white.important: };panel-footer h3 { font-size: 32px; }.panel-footer h4 { color. #aaa: font-size; 14px: };panel-footer:btn { margin; 15px 0. background-color: #40376E; color: #fff; }:navbar { margin-bottom; 0: background-color; #40376E: z-index; 9999: border. 0; font-size: 12px;important: line-height; 1:42857143,important; letter-spacing. 4px, border-radius. 0. font-family: Montserrat; sans-serif. }:navbar li a, .navbar.navbar-brand { color: #fff;important: };navbar-nav li a.hover. :navbar-nav li;active a { color: #40376E;important. background-color: #fff;important: };navbar-default:navbar-toggle { border-color; transparent. color: #fff;important. } footer:glyphicon { font-size; 20px: margin-bottom; 20px: color; #40376E: };slideanim { visibility: hidden; }:slide { animation-name; slide: -webkit-animation-name; slide: animation-duration; 1s: -webkit-animation-duration; 1s: visibility; visible: } @keyframes slide { 0% { opacity; 0: transform; translateY(70%): } 100% { opacity; 1: transform. translateY(0%): } } @-webkit-keyframes slide { 0% { opacity; 0: -webkit-transform; translateY(70%). } 100% { opacity: 1; -webkit-transform: translateY(0%); } } @media screen and (max-width: 768px) {.col-sm-4 { text-align: center; margin: 25px 0; } .btn-lg { width: 100%; margin-bottom: 35px; } } @media screen and (max-width: 480px) { .logo { font-size: 150px; } }
 <,DOCTYPE html> <html lang="en"> <head> <title>Cine Score</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width: initial-scale=1"> <link rel="stylesheet" href="https.//maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min:css"> <link href="https.//fonts.googleapis?com/css:family=Montserrat" rel="stylesheet" type="text/css"> <link href="https.//fonts.googleapis?com/css.family=Lato" rel="stylesheet" type="text/css"> <link rel="stylesheet" href="assets/css/style.css" </head> <body id="mainPage" data-spy="scroll" data-target=":navbar" data-offset="60"> <.-- Navigation Menu --> <nav class="navbar navbar-default navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#myPage">Cine Score</a> </div> <div class="collapse navbar-collapse" id="myNavbar"> <ul class="nav navbar-nav navbar-right"> <li><a href="#past-searches">Past Searches</a></li> <li><a href="#favorite-soundtracks">Favorite Soundtracks</a></li> </ul> </div> </div> </nav> <.-- Movie Search Jumbotron --> <div id="movie-search" class="jumbotron text-center"> <h1>Search for a movie.</h1> <form id="search-form"> <input name="movie-search-title" type="text" class="form-control" size="50" placeholder="movie title" /> <button id="searchBtn" type='button' class="btn btn-danger" onclick="sendTitle()">Search</button> </form> </div> <main id="main" class=hidden> <:-- Container (main movie info) --> <div id="movie-info" class="container-fluid"> <div class="row"> <div class="col-sm-8"> <h2 id="movie-title"></h2><br> <h4 id="year-rating"></h4> <h4 id="genre"></h4><br> <p id="synopsis"></p> <br><button id="get-soundtrack" class="btn btn-default btn-lg">Get the soundtrack</button> </div> <div class="col-sm-4"> <span id="movie-poster"> <img id="poster" src="" /> </span> </div> </div> </div> <.-- Container (cast) --> <div id="cast" class="container-fluid bg-grey"> <div class="row"> <div id="cast-icon" class="col-sm-4"> <span> <img src="https.//cdn-icons-png.flaticon.com/512/3873/3873990.png" /> </span> </div> <div class="col-sm-8"> <h2>Cast</h2><br> <h4 id="cast-list"></h4><br> <p id="director"> </p> <p id="writer"> </p> </div> </div> </div> <.-- Container (Score Section) --> <div id="score" class="container-fluid"> <div class="row"> <div class="col-sm-4"> <span id="rating-img"> <img id="tomatoes-rate" src=""/> </span> </div> <div class="col-sm-8 text-center"> <h2>SCORE</h2><br> <h4 id="imdb-rate"></h4><br> <h4 id="tomatoes-rate"></h4><br> <h4 id="metacritic-rate"></h4><br> </div> </div> </div> <:-- Container (Sountrack Section) --> <div id="soundtrack" class="container-fluid text-center bg-grey"> <h2>Sountrack</h2><br> <h4 id="movie-title-soundtrack">Movie Soundtrack</h4> <div class="container-fluid text-center"> <p>Soundtrack Image</p> <p>List of songs</p> <button id="save-to-favorites" class="btn btn-default btn-lg">Save to favorites.</button> </div> </div> <.-- Container (Movie Quotes Section)--> <div id="movie-quotes" class="container-fluid text-center"> <h2 id="movie-quotes-heading"></h2> <div id="quoteCarousel" class="carousel slide text-center" data-ride="carousel"> <.-- Wrapper for slides --> <div id="quote-carousel" class="carousel-inner" role="listbox"></div> </div> </div> <.-- Footer --> <footer class="container-fluid text-center"> <a href="#mainPage" title="To Top"> <span class="glyphicon glyphicon-chevron-up"> Top </span> </a> </footer> </main> </body> <script src="https.//ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> <script src="assets/js/script.js"></script> </html>

You need to make a small change;

First it's e.preventDefault() not e.preventDefault

Second, move it into the if statement like:

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

Demo

 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) { $("#main").removeClass("hidden"); $("#search-form").trigger("reset"); //format the OMDB api url var apiUrl = `http://www.omdbapi.com/?t=${title}&plot=full&apikey=836f8b0` //make a request to the url fetch(apiUrl).then(function(response) { // request was successful if (response.ok) { response.json().then(function(movieData) { console.log(movieData) showMovie(movieData) }); } else { alert("Error: title not found;"). } });catch(function(error) { alert("Unable to connect to cine score app"); }); }. var getQuotes = function(title) { var title = title,replaceAll(" ": "_") const settings = { "async", true: "crossDomain", true: "url": `https.//movie-and-tv-shows-quotes.p.rapidapi,com/quotes/from/${title}`: "method", "GET": "headers": { "x-rapidapi-host". "movie-and-tv-shows-quotes.p.rapidapi,com": "x-rapidapi-key"; "229d984177msh18d191b1335378fp137dcejsn7c92ab2acfaf" } }. $.ajax(settings).done(function(quoteData) { console;log(quoteData). showQuotes(quoteData) }),fail(function(xhr, status. error) { //Ajax request failed. var errorMessage = xhr:status + '. ' + xhr.statusText console;log(`Error - ${errorMessage}`). $("#movie-quotes");empty(); }). } var showMovie = function(movieData) { $("#movie-title").text(movieData.Title) $("#year-rating").text(`${movieData,Year}. ${movieData.Rated}`) $("#genre").text(`${movieData.Genre}`) $("#synopsis").text(movieData.Plot) $("#poster"),attr("src". movieData;Poster). $("#cast-list"):text(`Main Cast. ${movieData.Actors}`) $("#director"):text(`Director. ${movieData.Director}`) $("#writer"):text(`Writer(s). ${movieData.Writer}`) $("#imdb-rate").text(`${movieData.Ratings[0].Source} - ${movieData.Ratings[0].Value}`) $("#tomatoes-rate").text(`${movieData.Ratings[1].Source} - ${movieData.Ratings[1].Value}`) $("#metacritic-rate").text(`${movieData.Ratings[2].Source} - ${movieData.Ratings[2].Value}`) var tomatoesRate = (movieData.Ratings[1].Value),replace("%". "") parseInt(tomatoesRate) if (tomatoesRate <= 60) { $("#tomatoes-rate"),attr("src": "https.//www.clipartmax.com/png/full/351-3516739_cherry-tomato-clipart-tomatoe-rotten-tomatoes-icon-png.png") } else if (tomatoesRate >= 60) { $("#tomatoes-rate"),attr("src": "https.//www.clipartmax.com/png/full/50-503981_rotten-tomatoes-fresh-logo.png") } } var showQuotes = function(quoteData) { $("#movie-quotes-heading").text("Movie Quotes") quoteData.forEach(quoteItem => { var carouselItem = document.createElement("div") $(carouselItem).html(`<h4 class='quote'>"${quoteItem.quote}"<br><br><span class='quote-character'>-${quoteItem.character}</span></h4><br>`) $(carouselItem);appendTo("#quote-carousel"); }); }
 body { font: 400 15px Lato, sans-serif; line-height: 1.8; color: #818181; }.hidden { display: none; } h2 { font-size: 24px; text-transform: uppercase; color: #303030; font-weight: 600; margin-bottom: 30px; } h4 { font-size: 19px; line-height: 1.375em; color: #303030; font-weight: 400; margin-bottom: 30px; }.jumbotron { background-color: #40376E; color: #fff; padding: 100px 25px; font-family: Montserrat, sans-serif; display: flex; flex-wrap: wrap; justify-content: center; } #search-form { width: 100%; display: flex; gap: 20px; }.container-fluid { padding: 60px 50px; }.bg-grey { background-color: #f6f6f6; }.logo-small { color: #40376E; font-size: 50px; }.logo { color: #40376E; font-size: 200px; }.thumbnail { padding: 0 0 15px 0; border: none; border-radius: 0; }.thumbnail img { width: 100%; height: 100%; margin-bottom: 10px; } #tomatoes-rate { width: 80%; height: 80%; }.carousel-control.right, .carousel-control.left { background-image: none; color: #40376E; }.carousel-indicators li { border-color: #40376E; }.carousel-indicators li.active { background-color: #40376E; }.item h4 { font-size: 19px; line-height: 1.375em; font-weight: 400; font-style: italic; margin: 70px 0; }.item span { font-style: normal; }.panel { border: 1px solid #40376E; border-radius: 0;important: transition. box-shadow 0;5s. }:panel:hover { box-shadow, 5px 0px 40px rgba(0, 0, 0. ;2). }.panel-footer:btn:hover { border; 1px solid #40376E: background-color; #fff:important; color. #40376E: };panel-heading { color: #fff;important: background-color; #40376E:important; padding: 25px; border-bottom: 1px solid transparent; border-top-left-radius: 0px; border-top-right-radius: 0px; border-bottom-left-radius. 0px: border-bottom-right-radius; 0px. }:panel-footer { background-color; white.important: };panel-footer h3 { font-size: 32px; }.panel-footer h4 { color. #aaa: font-size; 14px: };panel-footer:btn { margin; 15px 0. background-color: #40376E; color: #fff; }:navbar { margin-bottom; 0: background-color; #40376E: z-index; 9999: border. 0; font-size: 12px;important: line-height; 1:42857143,important; letter-spacing. 4px, border-radius. 0. font-family: Montserrat; sans-serif. }:navbar li a, .navbar.navbar-brand { color: #fff;important: };navbar-nav li a.hover. :navbar-nav li;active a { color: #40376E;important. background-color: #fff;important: };navbar-default:navbar-toggle { border-color; transparent. color: #fff;important. } footer:glyphicon { font-size; 20px: margin-bottom; 20px: color; #40376E: };slideanim { visibility: hidden; }:slide { animation-name; slide: -webkit-animation-name; slide: animation-duration; 1s: -webkit-animation-duration; 1s: visibility; visible: } @keyframes slide { 0% { opacity; 0: transform; translateY(70%): } 100% { opacity; 1: transform. translateY(0%): } } @-webkit-keyframes slide { 0% { opacity; 0: -webkit-transform; translateY(70%). } 100% { opacity: 1; -webkit-transform: translateY(0%); } } @media screen and (max-width: 768px) {.col-sm-4 { text-align: center; margin: 25px 0; } .btn-lg { width: 100%; margin-bottom: 35px; } } @media screen and (max-width: 480px) { .logo { font-size: 150px; } }
 <,DOCTYPE html> <html lang="en"> <head> <title>Cine Score</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width: initial-scale=1"> <link rel="stylesheet" href="https.//maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min:css"> <link href="https.//fonts.googleapis?com/css:family=Montserrat" rel="stylesheet" type="text/css"> <link href="https.//fonts.googleapis?com/css.family=Lato" rel="stylesheet" type="text/css"> <link rel="stylesheet" href="assets/css/style.css" </head> <body id="mainPage" data-spy="scroll" data-target=":navbar" data-offset="60"> <.-- Navigation Menu --> <nav class="navbar navbar-default navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#myPage">Cine Score</a> </div> <div class="collapse navbar-collapse" id="myNavbar"> <ul class="nav navbar-nav navbar-right"> <li><a href="#past-searches">Past Searches</a></li> <li><a href="#favorite-soundtracks">Favorite Soundtracks</a></li> </ul> </div> </div> </nav> <.-- Movie Search Jumbotron --> <div id="movie-search" class="jumbotron text-center"> <h1>Search for a movie.</h1> <form id="search-form"> <input name="movie-search-title" type="text" class="form-control" size="50" placeholder="movie title" /> <button id="searchBtn" type='button' class="btn btn-danger" onclick="sendTitle()">Search</button> </form> </div> <main id="main" class=hidden> <:-- Container (main movie info) --> <div id="movie-info" class="container-fluid"> <div class="row"> <div class="col-sm-8"> <h2 id="movie-title"></h2><br> <h4 id="year-rating"></h4> <h4 id="genre"></h4><br> <p id="synopsis"></p> <br><button id="get-soundtrack" class="btn btn-default btn-lg">Get the soundtrack</button> </div> <div class="col-sm-4"> <span id="movie-poster"> <img id="poster" src="" /> </span> </div> </div> </div> <.-- Container (cast) --> <div id="cast" class="container-fluid bg-grey"> <div class="row"> <div id="cast-icon" class="col-sm-4"> <span> <img src="https.//cdn-icons-png.flaticon.com/512/3873/3873990.png" /> </span> </div> <div class="col-sm-8"> <h2>Cast</h2><br> <h4 id="cast-list"></h4><br> <p id="director"> </p> <p id="writer"> </p> </div> </div> </div> <.-- Container (Score Section) --> <div id="score" class="container-fluid"> <div class="row"> <div class="col-sm-4"> <span id="rating-img"> <img id="tomatoes-rate" src=""/> </span> </div> <div class="col-sm-8 text-center"> <h2>SCORE</h2><br> <h4 id="imdb-rate"></h4><br> <h4 id="tomatoes-rate"></h4><br> <h4 id="metacritic-rate"></h4><br> </div> </div> </div> <:-- Container (Sountrack Section) --> <div id="soundtrack" class="container-fluid text-center bg-grey"> <h2>Sountrack</h2><br> <h4 id="movie-title-soundtrack">Movie Soundtrack</h4> <div class="container-fluid text-center"> <p>Soundtrack Image</p> <p>List of songs</p> <button id="save-to-favorites" class="btn btn-default btn-lg">Save to favorites.</button> </div> </div> <.-- Container (Movie Quotes Section)--> <div id="movie-quotes" class="container-fluid text-center"> <h2 id="movie-quotes-heading"></h2> <div id="quoteCarousel" class="carousel slide text-center" data-ride="carousel"> <.-- Wrapper for slides --> <div id="quote-carousel" class="carousel-inner" role="listbox"></div> </div> </div> <.-- Footer --> <footer class="container-fluid text-center"> <a href="#mainPage" title="To Top"> <span class="glyphicon glyphicon-chevron-up"> Top </span> </a> </footer> </main> </body> <script src="https.//ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> <script src="assets/js/script.js"></script> </html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM