Retrieve information from a JSON file according to the provided input

Can someone help me fetch data based on user input in JavaScript?

When the input is 'Royal Python', I'm supposed to retrieve details about it. However, the code provided gives an error stating 'The file you asked for does not exist'. Even though the value goes into 'fname', I'm unsure if the function correctly retrieves data from the array. Is there a more concise way to achieve this? Any suggestions would be appreciated.

I've included my JavaScript code and webpage layout below:

<!DOCTYPE html> 
<html> 
<body>  

<form> <input type="text" name="fname" required> 
<button onclick="myFunction()">OK</button>
</form>
<p id="demo"></p>  
<script> var text = '{"animals":[' + 
'{"Common Name":"Royal Python","Order":"Squamata","Family":"Boidae","Genus":"Python","Species":"regius","Zoo":"Blackpool Zoo","Number":4 },' + 
'{"Common Name":"Emperor Penguin","Order":"Sphenisciformes","Family":"Spheniscidae","Genus":"Aptenodytes","Species":"forsteri","Zoo":"Welsh Mountain Zoo","Number":35 },' +
'{"Common Name":"Chimpanzee","Order":"Primates","Family":"Pongidae","Genus":"Pan","Species":"troglodytes","Zoo":"Blackpool Zoo","Number":8 }]}';  

obj = JSON.parse(text);  


//function to fetch data based on input

function myFunction(fname) {
var ani = ""; 
if (document.getElementByname("fname")="Royal Python")   
var ani =  document.getElementById("demo").innerHTML = obj.animals[0].Zoo + " " + obj.animals[0].Species; }}  </body> </html>

Answer №1

One potential solution to your issue involves using a for loop to iterate through each index of the animal array in search of a match. This matching process is also designed to be case-insensitive.

<!DOCTYPE html>
<html>

<body>
    <p id="demo"></p>
    <input type="text" name="fname" required>
    <button onclick="fetchAnimal()">OK</button> `enter code here`
    <script>
    var animalsArr = [{
        "commonName": "Royal Python",
        "order": "Squamata",
        "family": "Boidae",
        "genus": "Python",
        "species": "regius",
        "zoo": "Blackpool Zoo",
        "number": 4
    }, {
        "commonName": "Emperor Penguin",
        "order": "Sphenisciformes",
        "family": "Spheniscidae",
        "genus": "Aptenodytes",
        "species": "forsteri",
        "zoo": "Welsh Mountain Zoo",
        "number": 35
    }, {
        "commonName": "Chimpanzee",
        "order": "Primates",
        "family": "Pongidae",
        "genus": "Pan",
        "species": "troglodytes",
        "zoo": "Blackpool Zoo",
        "number": 8
    }]

    function fetchAnimal() {
        var i;
        var len = animalsArr.length;
      
        // convert input name to lower-case
        var name = document.getElementsByName('fname')[0].value.toLowerCase();

        for (i = 0; i < len; i++) {
            // check to see if lower-case input matches any lower-case animal names (ignores case sensitivity)
            if (animalsArr[i].commonName.toLowerCase() === name) {
                document.getElementById('demo').innerHTML = animalsArr[i].zoo + ' ' + animalsArr[i].species;
            }
        }
    }
    </script>
</body>

</html>

Note: To enhance interactivity on the page, it's advisable to transfer the JS code into an external script file.

Answer №2

It seems like there are a few issues that need to be addressed in the code:

document.getElementByname("fname")="Royal Python"
should actually be
document.getElementsByName("fname")[0].value == "Royal Python"

Instead of writing out text strings and then parsing them as JSON, consider using a JavaScript object for simplicity.

When trying to determine the animal, utilizing Array.findIndex() can be more efficient if supported by your browser.

Below is an example with the necessary corrections:

var obj = {animals:[{CommonName:"Royal Python",Order:"Squamata",Family:"Boidae",Genus:"Python",Species:"regius",Zoo:"Blackpool Zoo",Number:4 }, {CommonName:"Emperor Penguin",Order:"Sphenisciformes",Family:"Spheniscidae",Genus:"Aptenodytes",Species:"forsteri",Zoo:"Welsh Mountain Zoo",Number:35}, {CommonName:"Chimpanzee",Order:"Primates",Family:"Pongidae",Genus:"Pan",Species:"troglodytes",Zoo:"Blackpool Zoo",Number:8}]};

//function to fetch data based on input
function myFunction() {
var name = document.getElementsByName("fname")[0].value;
var index = obj.animals.findIndex(function(item) {
return item.CommonName === name;
});
if (index >= 0) {
document.getElementById("demo").innerHTML = obj.animals[index].Zoo + " " + obj.animals[index].Species;
}
}
<input type="text" name="fname" required value="Royal Python">
<button onclick="myFunction()">OK</button>
<p id="demo"></p>

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

The bidirectional bindings within the component are malfunctioning

I just started learning Angular and I'm currently working on a small project. After following tutorials on two-way bindings, I attempted to implement it in my project. However, when I try to set values in the HTML for my component, it doesn't see ...

Iterating through a dataset in JavaScript

Trying to find specific information on this particular problem has proven challenging, so I figured I would seek assistance here instead. I have a desire to create an arc between an origin and destination based on given longitude and latitude coordinates. ...

What are some techniques for ensuring a CSS div remains stable and intact when adjusting the browser size?

Is there a way to prevent the entire website from resizing when you minimize or maximize your browser? I want the website size to adjust in proportion to your resize without reorganizing everything. How can this be achieved while maintaining the site lengt ...

How can I prevent SweetAlert from automatically focusing when it first opens?

I recently integrated SweetAlert into my project and customized the buttons like this: swal("A wild Pikachu appeared! What do you want to do?", { buttons: { cancel: "Run away!", catch: { text: "Throw Pokéball!", value: "catch", ...

A guide on incorporating and utilizing third-party Cordova plugins in Ionic 5

Attempting to implement this plugin in my Ionic 5 application: https://www.npmjs.com/package/cordova-plugin-k-nfc-acr122u I have added the plugin using cordova plugin add cordova-plugin-k-nfc-acr122u but I am unsure of how to use it. The plugin declares: ...

Semantic-release failing to generate a new version update for package

I'm in the process of setting up semantic release for my NPM package to automate deployment with version updates. However, after migrating from an old repo/npm package to a new one, I'm facing issues with semantic versioning not creating a new re ...

Passing a service into a directive results in an undefined value

Can someone help me understand why a service I am injecting into a directive is returning undefined in certain instances? If you would like to take a look at the code, here is a plunker link: https://plnkr.co/edit/H2x2z8ZW083NndFhiBvF?p=preview var app = ...

IntelliJ does not support the use of newlines within Vue.js component templates

While working with Vue.js in IntelliJ IDEA, I encountered a small problem related to defining component templates. The issue is that IntelliJ seems to struggle when the template spans more than one line and attempts to concatenate them together. For examp ...

Exploring the Functionality of Cookies in Nuxt 3 API Endpoints and Middlewares

Can cookies be utilized on the server side in Nuxt 3? For instance, I need to set a cookie in an API and then access its data in middleware: // ~/server/api/testApi.ts export default defineEventHandler(event => { /* setCookie('myCookie', ...

Is it possible for me to set a timer on the 'keyup' event in order to decrease the frequency of updates?

The code I currently have is functional: $wmdInput.on('keyup', function () { var rawContent = $wmdInput.val(); scope.$apply(function () { ngModel.$setViewValue(rawContent); }); }); Unfortunately, it appears to slow down my t ...

Express displaying undefined when referring to EJS variable

After receiving valuable assistance from user Jobsamuel, I have been encountering challenges in displaying the data retrieved from an API call on a webpage: // EJS template to show API data. app.get('/activities', function (req, res) { if (re ...

Why do I keep getting an ExpressionChangedAfterItHasBeenChecked error after trying to update a random color in an

Is there a way to assign a random color from an array without causing the error message: "ExpressionChangedAfterItHasBeenChecked"? Even though the color of the chip changes quickly before the message appears, it seems like it's working. How can I reso ...

Stop the slider when a video pops up

Years ago, I had a slider created for me that supports both images and video with a timer. However, the issue I'm facing is that when the timer runs every 10 seconds, the video gets cut off if it's not finished playing. Below is the json file st ...

Issues with setSelectionRange functionality in JavaScript unit tests leading to unexpected behavior

Currently, I am utilizing the qunit framework to perform unit testing on interactions within an HTML element that has been dynamically created using jquery (specifically, var $textarea = $('')) in Chrome. Below is the code snippet I am employing ...

I want to retrieve a complete HTML page using an AJAX request

I am trying to retrieve the content of a specific page, but encountering issues when using this function: function getResult() { var url="http://service.semanticproxy.com/processurl/ftfu27m3k66dvc3r43bzfneh/html/http://www.smallbiztechnology.c ...

Tips on transmitting form information from client-side JavaScript to server-side JavaScript with Node.js

Having created an HTML page with a form, my goal is to capture user input and store it in a JSON file. However, I've run into some confusion... In the process, I utilized the express module to set up a server. My mind is juggling concepts such as AJA ...

Error: The route cannot be established within an asynchronous function

The following code snippet is from the api.js module, responsible for creating a test route: 'use strict'; module.exports = function (app) { console.log("before route creation"); app.get("/api/test", (req, res) => { ...

Sending JSON data through an HTTP POST request using Arduino

I am attempting to send JSON data using an Arduino. When running this code, I attempt to send the JSON data with a QueryString parameter. However, when I try this code, the server responds with a message stating that the QueryString format is incorrect, in ...

Guide to extracting a key from the route module with the help of vuex-router-sync

I have a Vuex store setup as shown below, and I am using vuex-router-sync to keep it in sync. This plugin adds a router module to my store. However, I am unsure of how to retrieve this object from the store since there are no associated getters with this m ...

I'm looking for assistance on how to execute a render right after making a put or delete request

class ProductApp extends Component { constructor() { super(); this.state = { currentProduct: null, items: [], }; this.handleUpdateSubmit= this.handleUpdateSubmit.bind(this); } componentDidMount() { axios.get('h ...