Utilize HTML onclick functionality with a submit button to query a JavaScript array, then showcase the specific data within the initial HTML div

I have been exploring YouTube tutorials in an attempt to learn how to effectively search for specific data entries within an array. Below is an example of a JavaScript array along with the use of console.log.

JavaScript Array Example:


var data = {
  username: "john",
  email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4b79730b0c180f0d0d65080406">[email protected]</a>",
  status: true,
  id: 25
};

var data = {
  username: "jIM",
  email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="91a3a6d1d6c2d5d7bfd2dedc">[email protected]</a>",
  status: false,
  id: 23
};

var data = {
  username: "Jane",
  email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fccec9bcbbafb8bad2bfb3b1">[email protected]</a>",
  status: false,
  id: 22
};

{
  console.log(data);
}

Below is an HTML snippet where I am attempting to create functionality that allows me to search the above JavaScript array and display/print the result in a specific div upon clicking a submit button.


<html>
<head>
<title>Get Value</title>;

    <script type="text/javascript">
    function getDisplay(){
    var username = document.getElementById("username").value;
    var email = document.getElementById("email").value;
    document.getElementById("display").innerHTML = "Username: " + username + "<br/>Email: " + email;
    }
</script>

</head>
<body>

  <div id="whole">
        Username : <input type="text" name="username" id="username">

        Email : <input type="email" name="email" id="email"></br>
        
        <button onclick=getDisplay()>Submit</button>

  </div>
  
  <div id="display">
  </div>

</body>
</html>

If you have any recommendations on videos or resources that could assist me in my learning process, it would be greatly appreciated.

Answer №1

What you need to do initially is create an array with objects like the one shown below:

var data=[{
          username: "john",
          email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2d1f156d6a7e696b036e6260">[email protected]</a>",
          status: true ,
          id: 25
         },
         {
         username: "jIM",
         email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c6f4f18681958280e885898b">[email protected]</a>",
         status: false,
         id: 23
         }];

This array consists of objects, allowing you to manipulate it as needed. You can use Object.keys(data) for further operations.

Answer №2

If your JSON data is structured in this way and your search function follows this logic.

const userData = [
  {
    username: "john",
    email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d2e0ea9295819694fc919d9f">[email protected]</a>",
    status: true,
    id: 25
  },
  {
    username: "jIM",
    email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d6e4e19691859290f895999b">[email protected]</a>",
    status: false,
    id: 23
  },
  {
    username: "Jane",
    email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a19394e1e6f2e5e78fe2eeec">[email protected]</a>",
    status: false,
    id: 22
  }
];


function displayUserData(){
    const usernameInput = document.getElementById("username").value;
    const emailInput = document.getElementById("email").value;

    userData.forEach(function(item, index){
      if((item.username === username) && (item.email === email)) {
        const displayInfo = "<li><b>User Name</b>: "+ item.username +"</li>"+
              "<li><b>Email</b>: "+ item.email +"</li>"+
              "<li><b>Status</b>: "+ item.status +"</li>"+
              "<li><b>ID</b>: "+ item.id +"</li>";     
        $("#display").html(displayInfo);
      }
    });

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<div id="whole">
  Username : <input type="text" name="username" id="username"></br>
  Email : <input type="email" name="email" id="email"></br>
  <button onclick=displayUserData()>Submit</button>
</div>
<div id="display"></div>

Answer №3

The structure for an array of objects should be as follows:

      var arr = [{
                  username: "john",
                  email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8fbdb7cfc8dccbc9a1ccc0c2">[email protected]</a>",
                  status: true,
                  id: 25
                 },
                {
                  username: "jIM",
                  email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0e3c394e495d4a48204d4143">[email protected]</a>",
                  status: false,
                  id: 23
                },
                {
                  username: "Jane",
                  email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f4c6c1b4b3a7b0b2dab7bbb9">[email protected]</a>",
                  status: false,
                  id: 22
                }
               ]

In your code, you need to perform the following action :

    <html>
     <head>
        <title>get value</title>


    <script type="text/javascript">

    var arr = [/*Your data here */];

    function getDisplay(){
           var username = document.getElementById("username").value;
           var email = document.getElementById("email").value;

           document.getElementById("display").innerHTML = "username" +  username + "<br/>email" + email;

      for(let i = 0; i < arr.length; i++) {
          let element = arr[i];
          //Your search logic goes here
      }
    }
</script>

</head>
  <body>

      <div id="whole">
              Username : <input type="text" name="username" id="username">

        Email : <input type="email" name="email" id="email"></br>


        <button onclick=getDisplay()>Submit</button>

  </div>
  <div id="display">
  </div>


</body>
</html>

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

An array of objects, where each object contains an array populated with variable names instead of their corresponding values

I have created a custom object class SalesReportObject { public $eventname = ""; public $v_firstname = ""; public $v_secondname = ""; public $soldStock = array(); function Push($productname, $soldquantity) { $soldStock[$pro ...

What makes arrays quicker than lists in Haskell?

Currently delving into Haskell, I find myself pondering the following: In Haskell, the List type serves as a fundamental data type. Interestingly, arrays in Haskell are built upon lists. These arrays consist of indices [Ix a] and function representations ...

Using Angular to display the initially selected option value in a select dropdown menu

Struggling to set the default selected option in a select input using Angular. I've tried several solutions with no success. It's baffling why this is proving so difficult for me. Any assistance would be greatly appreciated, thank you. The selec ...

The function is receiving an empty array of objects

This code is for an Ionic app written in typescript: let fileNames: any[] = []; fileNames = this.getFileNames("wildlife"); console.log("file names:", fileNames); this.displayFiles(fileNames); The output shows a strange result, as even though there ar ...

Sending information to ajax request upon successful completion

I needed to transfer the output of the json_encode() function to jQuery. Once successful, I intended to refresh a specific division. Action: <a id="js-delete-file" href="#" data-url="<?php echo site_url('document_items/remove/'. $value[&a ...

Setting up only two input fields side by side in an Angular Form

I'm fairly new to Angular development and currently working on creating a registration form. I need the form to have two columns in a row, with fields like Firstname and Lastname in one row, followed by Phone, Email, Password, and Confirm Password in ...

Splitting an array into multiple arrays with distinct names: A step-by-step guide

I have a data set that looks like this: [A,1,0,1,0,1,B,1,0,0,1,A,1]. I want to divide this array into smaller arrays. Each division will occur at the positions where "A" or "B" is found in the original array. The new arrays should be named with the prefix ...

Transform identical words in a website's content into clickable buttons

I'm currently in the process of developing a Chrome extension that scans a website for specific keywords and then converts them into interactive buttons. However, I've encountered an issue where changing the text causes the image path to become c ...

What purpose does a Java Char array serve?

Below is a Java code snippet that involves the BigInteger class: import java.math.BigInteger; public class Main { public static void main (String[] args) { BigInteger num = new BigInteger("123456789101112131415"); String str; ...

What is the ideal event to trigger a response when the user completes entering text into the search field in Vue.js?

I am currently utilizing a text field from the Vuetify library to filter a table within my application. <v-text-field style="min-width: 300px;" v-model="filterString" label="Search" /> The functionality is straigh ...

Modify the CSS styles (which were set by a preceding function) upon resizing the screen using Javascript

In the mobile version of a website (width less than 620px), there is a button in the header. Clicking this button triggers the "mobileNav" function, which toggles the visibility of the mobile navigation between "display: none;" and "display: flex;". This f ...

Strategies for efficiently updating specific objects within a state array by utilizing keys retrieved from the DOM

I am trying to figure out how to use the spread operator to update state arrays with objects that have specific ids. Currently, I have an array called "todos" containing objects like this: todos: [ { id: "1", description: "Run", co ...

ObjectMapper for iOS, parsing JSON data containing arrays

I have a query: How can I convert this JSON response into an object using Hearst-DD/ObjectMapper? { "errors": [ { "code": "404", "message": "Wrong id" } ] } With SwiftyJSON, I would use: json["errors"][0]["code"] Bu ...

Execute and showcase code without redundancies

I have been exploring a way to store JavaScript code within an object and execute specific parts of it upon the user clicking a button. Here's what I've come up with so far: var exampleCode = { test: "$('body').css('background ...

The nested router fails to provide the next callback containing the value of 'route'

While developing a middleware handler, I ran into an interesting issue where passing the route string as an argument for the next callback resulted in a value of null. Here's an example to illustrate this: var express = require('express') ...

JavaScript: How can I remove it when I click anywhere on the webpage with onClick?

A challenge I'm facing involves creating a form with an input field that changes its border color when clicked. My goal is for the border to return to its original color when clicking anywhere else on the page. -HTML <form action=""> ...

Exploring the vueJS canvas life cycle and transitioning between components

Struggling with displaying Vue components that contain a canvas with different behaviors. Looking to switch components using v-if and passing different properties. Here's a small example: Currently, when switching from 'blue' to 'red ...

Draggable shape using Three.js

I have been studying the code for a draggable cube from this link. However, I am struggling to understand the purpose of creating an offset between the plane and the selected object, as seen in this section of the code: function onDocumentMouseDown( even ...

Combining JavaScript functions and Vue.js methods through chaining

When working within a Vue component, I have a scenario where I am invoking a function from a separate JavaScript file. The requirement is to then trigger a method within my component once the first function has finished executing: Here is an example of my ...

Using form.submit() alongside preventDefault() will not yield the desired outcome

My login form needs to either close the lightbox or update the error box based on the success of the login attempt. I suspect the issue lies with the onclick="formhash(this.form, this.form.password);" which is a JavaScript function that hashes a passwor ...