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

HTMLElement addition assignment failing due to whitespace issues

My current challenge involves adding letters to a HTMLElement one by one, but I'm noticing that whitespace disappears in the process. Here's an example: let s = "f o o b a r"; let e = document.createElement('span'); for (let i ...

Incorporating location markers onto a Google map using a JSON array

Here is some code I've been struggling with function fetchData() { var url = "http://localhost/Geocording/api.php"; $.getJSON(url, function (data) { var json = data; for (var i = ...

The controller method in Laravel is not being triggered by AJAX

In my blade layout file, I have some code that is included in my view multiple times using the @include.layout("blade file link") syntax. When a button is pressed, I want to call a controller function. This works fine without AJAX, but when AJAX is added, ...

Ingesting a PDF stream into a JSP document

How can I display a PDF report inside a JSP? I have the PDFstream available using the following code private void generatePDFReport(OutputStream stream, JasperPrint jasperPrint) throws JRException { JRPdfExporter jrpdfexporter = new JRPdfExporter(); jrp ...

"Encountered a Json error with a bizarre character causing the string

After extracting some json data from a website, I encountered an issue when trying to parse it using vscode. I kept getting an 'unexpected end of string' error on the "content" line: Here is the json: { "name": "Anna Vergnas", "date" ...

Data Binding in AngularJS appears to be non-functional

Experimenting with AngularJS, I created a small code snippet that doesn't seem to bind data properly. Here is the HTML and JS code for those who prefer not to visit the provided link: first.html <!doctype html> <html ng-app="firstApp"> & ...

Converting multiple rows of data from MySQL into JSON format

Currently, I am working on a project that involves displaying multiple rows of MySQL JSON data in an HTML table using PHP and jQuery. The process includes input from a search box on the front end. The layout of my HTML table on the search page is structur ...

How to fetch database results using jQuery AJAX and PHP's JSON encoding

I am currently working on a PHP code that is triggered using jQuery AJAX to query a database and retrieve results, which are then encoded into JSON format. //$rows is another query foreach($rows as $row) { $sql = 'SELECT field1, field2 FROM tabl ...

Sharing a collection of data fields

I am dealing with dynamic fields within a Bootstrap three form that is divided into tabs. Due to the removal of form tags in the modal, I have my fields set up outside. I can successfully post the values using jQuery attribute selectors like $("input[name ...

"Looping through each item in a list using Angular

I have a setup for an HTTP request that will return the list of products once all promises are fulfilled. My objective is to initially set the opacity of these products to 0, and then use a forEach loop to add a class that sets their opacity to 1. While ...

Deep Dive into TypeScript String Literal Types

Trying to find a solution for implementing TSDocs with a string literal type declaration in TypeScript. For instance: type InputType = /** Comment should also appear for num1 */ 'num1' | /** Would like the TSDoc to be visible for num2 as well ...

JavaScript (specifically, using jQuery) in conjunction with AJAX

After using validation with jQuery in JavaScript and applying it to ASP.NET controls within an AJAX update panel, I encountered a problem. The validations are working correctly, but the event of the button control is still being executed despite the valida ...

The backbone module is experiencing formatting issues

I'm new to learning backbone.js. I've created the example below, but unfortunately, it's not functioning properly. Can someone please help me understand why? The goal is to simply display the name within my div element. (function($) { ...

Mysterious data organization - transform into an object

As I interact with an API, there is a value that I cannot quite pinpoint. My goal is to transform this string into a JavaScript object, but the process seems complex and confusing. Does anyone have insight on what this data represents and how it can be co ...

Using JavaScript to auto-scroll a textarea to a certain position

Is there a way to change the cursor position in a textarea using JavaScript and automatically scroll the textarea so that the cursor is visible? I am currently using elem.selectionStart and elem.selectionEnd to move the cursor, but when it goes out of view ...

A dynamic search feature implemented with PHP, MySQL, and AJAX

I have implemented an ajax call to fetch data from my mysql database when searching for users. Below is the corresponding html code; <input type="text" id="partnerName" name="partnerName" class="form-control" placeholder="Type to search partners...."& ...

Tips for showcasing the information from a JSON document in React

I have a JSON file stored statically in my public directory and I'd like to show its content within a React component (specifically NextJS). The goal is to simply render the JSON as it is on the page. import data from '../../public/static/somedat ...

Issue with ngModelChange and change events not functioning properly in Internet Explorer 11

Within a text input field, I have implemented single-way binding in addition to utilizing a number formatter pipe. I have also set up an (ngModelChange) event handler to remove any commas that are added by the number formatter, and a (change) event to tri ...

Getting the content of a textarea within a v-for loop collection

Exploring this particular situation In a .vue file within the template <div v-for="(tweet, index) in tweets"> <div class="each_tweet"> <textarea v-on:keyup="typing(index)" placeholder="Share your thoughts">{{ tweet.c ...

A JavaScript function that yields no value is undefined

In my AngularJS project, I have a function that makes a GET request to the backend multiple times and returns data. Here is an example of how the function is used: function getFunction(inputData) { $http.get('request URL', { params: 'so ...