Guide to attaching click and keydown events to an input field using Vanilla JavaScript

I am currently working on a project for freecodecamp where I have successfully created a functional example. However, there are a few things that I'm struggling to figure out.

Firstly, I need help with executing an AJAX request by either typing in the input field and pressing enter or clicking on the button.

Secondly, when I type something in the input field and press enter, the results display on the webpage. But if I try to enter new text and press enter again, the previous results disappear instead of showing additional results. I want the new results to append below the old ones without removing them.

I've looked at other posts that use jQuery but I prefer to stick to plain JavaScript. Below is my code:

Answer №1

I have made some updates to your code, check this fiddle for the revised version Ajax call on button click

Please test if the changes meet your requirements.

Below are the modifications I implemented in your code:

  • The event "keydown" has been replaced with "keyup" event to capture key press values correctly.
  • I divided the function calls between search button click event and input key event for clarity.
  • An ID has been assigned to the search input field to access its value during "requestData()" function execution.
  • If there is an "input type = 'button'" inside a form, clicking the button will submit the form.
  • Added "event.preventDefault()" as the first line in "requestData()" to prevent automatic form submission when pressing Enter.
  • Included a paragraph to display result statistics.
  • Changed the line from document.myForm.innerHTML += to
    document.getElementById("results_stats").innerHTML
    .

Hope these updates prove useful.

HTML :-

<div class="container-wrapper">
<header>
  <h1> Wikipedia Viewer </h1>
  <form action="" name="myForm">
    <input type="text" name="search" id="txt_search" /><input type="button" name="searchBtn" value="Search"/>
    <br>
    <input type="button" name="btnRandom" class="random" value="Random Article"/>
  <p id="results_stats"></p>
  </form>
</header>

<div class="container">
    <ul id="list"></ul>
</div>

JAVASCRIPT :-

    var url = 'https://en.wikipedia.org/w/api.php?action=opensearch&datatype=json&limit=10&origin=*&search=';
var inputSearch = document.myForm.search;
var searchBtn = document.myForm.searchBtn;
var list = document.getElementById("list");
var random = document.getElementsByClassName('random')[0];

random.addEventListener("click" , function(){
  window.open("https://en.wikipedia.org/wiki/Special:Random");
});

function getDataFromInputBox(e){
  console.log("Value Entered"+inputStr);

  if ( e.keyCode === 13 ) {
      requestData(e);
  }
}
function requestData(e) {
  e.preventDefault();
  console.log(e.target);
    var inputStr = document.getElementById("txt_search").value;
  if(inputStr != ""){
    console.log(inputStr);
  var request = new XMLHttpRequest();
  request.onreadystatechange = function () {
    if ( request.readyState === 4 ) {
      if ( request.status === 200 ) {
        var dataObj = JSON.parse(request.responseText);
        var titles = dataObj[1];
        var descriptions = dataObj[2];
        var links = dataObj[3];
        document.getElementById("results_stats").innerHTML = "<h2><span>" + links.length + "</span> results for \"" + "<span>" + inputStr + "</span>" +"\" </h2>"; 
        list.innerHTML = "";
        for ( var i = 0; i < titles.length; i++ ) {
          var li = "<li><a target='_blank' href=" + links[i] + ">" + titles[i] + "</a></li>";
          list.innerHTML += li;
        }
      }
      else {
        console.log("Server responded with following error code : " + request.status);
      }
    }
  };
  request.open("GET" , url + inputStr);
  request.send(null);
  //e.preventDefault(); 
  }
  else{
    document.getElementById("results_stats").innerHTML;
    list.innerHTML = "";
    alert("Enter a value");
  }
}

inputSearch.addEventListener("keyup" , getDataFromInputBox);
searchBtn.addEventListener("click" , requestData);
document.myForm.addEventListener("submit",requestData);

CSS :-

/* http://meyerweb.com/eric/tools/css/reset/ 
   v2.0 | 20110126
   License: none (public domain)
*/

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed, 
figure, figcaption, footer, header, hgroup, 
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
    margin: 0;
    padding: 0;
    border: 0;
    font-size: 100%;
    font: inherit;
    vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure, 
footer, header, hgroup, menu, nav, section {
    display: block;
}
body {
    line-height: 1;
}
ol, ul {
    list-style: none;
}
blockquote, q {
    quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
    content: '';
    content: none;
}
table {
    border-collapse: collapse;
    border-spacing: 0;
}

/* CSS reset ends here */

body {
    font-size: 16px;
    font-family: 'Oxygen', sans-serif;

}

.container-wrapper {
    margin: 0 auto;
    text-align: center;
    height: 100vh;

}

header {
    /*background-color: #fc3e5b;*/
    padding: 80px 0;
}

header h1 {
    font-family: 'Anton', sans-serif; 
    font-size: 70px;
    padding: 30px 0 80px 0;
    color: #fc3e5b;
}

form input , form button {
    padding: 10px 8px;
    font-size: 22px;
    border: 1px solid #fc3e5b;
    outline: 0;
    display: inline;
    margin: 0;
}

form button {
    background-color: #fc3e5b;
    color: #fff;
}

h2 {
    font-size: 25px;
    margin-top: 32px;
}

h2 span {
    font-weight:bold;
    color: #fc3e5b;
}
.random {
    padding: 22px 7px;
    border-radius: 100%;
    margin: 20px 0 15px 0;
}

.random:hover {
    border: 5px solid #fc3e6b;
}

#list {
    width: 75%;
    margin: 0 auto;
}

#list li {
    padding: 16px 8px;
    background-color: #fc3e5b;
    margin: 12px 0;
    text-align: left;
    font-size: 22px;
}

#list li a {
    text-decoration: none;
    color: #fff;
}

Answer №2

It appears that you are experiencing an issue where you need to retype your input after pressing enter, which suggests that the form is being submitted.

Your current conditional statement checks if the pressed key is 13 and then uses eg.preventDefault(), but it lacks passing the form submit event.

You can resolve this by updating your code as follows:

document.querySelector('form').addEventListener('submit', requestData(e));

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

Load upcoming and previous slides in advance

Currently, I have implemented a basic slideshow on my website. It functions properly, but I am interested in preloading the previous and next slides to enhance its speed. Is there anyone who can assist me with this request? ...

Each time a new client connects, socket.io replicates the information

Exploring Node.js and socket.io for the first time, I have developed a small application where a table is meant to be displayed in real-time via socket.io when a function is triggered through a websocket (function triggers an "emit"). However, I'm fac ...

Issues arise when attempting to transfer strings through ajax to a Node.js server that is utilizing express.js

On my website, I am encountering a problem where certain characters are being lost when I send strings to my Node.js server. // Client: microAjax("/foo?test="+encodeURI("this is ++ a test"), function callback(){}); // Server: app.get('/foo',fun ...

The jsonp typeahead feature is not populating the uib-typeahead form element

Trying to populate a uib-typeahead from the ui-bootstrap modules using a jsonp callback function in a factory method has been challenging. This is the factory function being used: autoCompleteCity: function(city){ return $http.jsonp("http://g ...

Which is better: storing an element in a variable or selecting it every time it's needed for efficiency?

When targeting an element multiple times, which method is more efficient? Consider Example 1: var el = $("#element"); el.html("foo"); el.html("bar"); Compare it to Example 2: $("#element").html("foo"); $("#element").html("bar"); Is there a noticeable ...

Issue with integrating the jquery tokeniput plugin in asp.net mvc 3

Having trouble integrating the jQuery Tokeninput plugin into my MVC application. Something seems off with the setup... The Code I'm Using: <input type="text" id="MajorsIds" name="MajorsIds" /> <script type="text/jav ...

What could be the reason my this.setState is not properly updating the array?

Is there something I'm overlooking? I've implemented the es6 style to add to an empty array in this.state, but nothing is being pushed to state. I should have a total of two elements inside the array, however, after console.logging, nothing is a ...

What is the best way to add multiple lines of text to a webpage using the span element?

Currently, I am developing a game that involves using a map, which consists of multiple lines. My question is whether it is possible to have the span tag cover multiple lines while ensuring that each line ends with a new line character. Below is an exampl ...

Trouble with implementing web methods through AJAX communication channel

my .cs code is auth_reg.aspx.cs (breakpoint shows the method is never reached) [WebMethod] public void ImageButton1_Click() { string strScript = "<script language='JavaScript'>alert('working')</script>"; Page.Regis ...

Scale transformation - I am aiming for it to exceed the limits, yet it remains contained within

Currently, I am working on enhancing my carousel by implementing a zoom effect when hovering over the images. However, I have encountered an issue where the image gets hidden within the div container and doesn't overflow as expected. I tried adjusting ...

Retrieve the identification number for each item within my array

I am working with an array of objects, each having a unique ID. My goal is to find the index of each object in the array. I am currently using Angular, however, I am restricted from using $index for this particular task. $scope.getObjectIndex = fun ...

When a cursor hovers over an image, a dark line appears

I wanted to create a hover effect where the image would enlarge when hovered over. I achieved this using a JavaScript function that applies the transform property with a scale of 1.2 to the picture. However, during the animation, a black line appears at th ...

What is the best way to present retrieved JSON data from a database in Node.js without using the JSON format?

Here is the code snippet: var http=require("http"); var fs = require("fs"); var express = require("express"); var app = express(); var path = require("path"); var mysql = require('mysql'); var ejs = require("ejs") var bodyParser = require(&apos ...

Guide on sending files through an API request with formData() using Vuejs and Axios

My goal is to utilize an API to upload a file to the server. The documentation on documenter.getpostman outlines how to use the API: --form 'type="1"' \ --form 'user_id="1"' \ --form 'file=@"/C:/U ...

Numerous HTML documents being uploaded to the server for a multitude of individuals

Currently, I am developing a game on a website where players create new rooms and are assigned specific roles with individual powers. Some players need to wait for input from others, creating a dynamic gameplay experience. Additionally, there are certain ...

Identifying Elements Generated on-the-fly in JavaScript

Currently, I am tackling the challenge of creating a box that can expand and collapse using regular JavaScript (without relying on jQuery). My main roadblock lies in figuring out how to effectively detect dynamically added elements or classes to elements a ...

How to disable the underline styling for autocomplete in a React Material UI component

Seeking assistance with removing underline styling and changing text color upon focus within the autocomplete component of React Material UI. Struggling to locate the specific style needing modification. Appreciate any help in advance! ...

What could be the reason for my Express server returning a 404 error for all files other than index.html?

Currently, I am delving into Node.js with Express in order to set up a small server for educational purposes. Strangely, every request made to files linked within my index.html file, such as the .css, .js, and image files, results in a response code 404. ...

How can I utilize the "remark" tool to handle Markdown files with URLs that don't adhere to Markdown formatting? Are there any supplemental plugins available for this

My markdown file has frontmatter and sometimes includes inline URLs that are not properly formatted with markdown syntax. I'm looking for a way to handle these non-markdown URLs within the markdown file - possibly by parsing them into HTML URLs using ...

JavaScript HTTP Requests

I came across this AJAX example in Stoyan Stefanov's book Object Oriented JavaScript on page 275. The example involves requesting three different files. I have a few questions that I was hoping someone could help me with! What does the line xhr.se ...