Get data from JSON based upon the input received - javascript

I need to fetch data based upon the input received.
For example, if the input is 'Royal python', I should get details of Royal python.but with the following code, i get error saying 'The file you asked for does not exist'. But I get the value into fname. But not sure if the function is correct to fetch data from from array.Also I wanted to know if there is any shorter way to do this. Please help?
I'm using JavaScript for this, my code and the web page look are below:
<!DOCTYPE html>
<html>
<body>
<form> <input type="text" name="fname" required>
<button onclick="myFunction()">OK</button> `enter code here`
</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>

Here is a solution to your problem that uses a for loop to check each index of the animal array for a match. This match will be case-insensitive also.
<!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 is the same as lower-case animal name (this ensures the match is case-insensitive)
if (animalsArr[i].commonName.toLowerCase() === name) {
document.getElementById('demo').innerHTML = animalsArr[i].zoo + ' ' + animalsArr[i].species;
}
}
}
</script>
</body>
</html>
Note: It is highly recommended move the JS code into an external script file if you intend to add more interactivity to the page.

There are a number of issues in your code:
document.getElementByname("fname")="Royal Python" should be document.getElementsByName("fname")[0].value == "Royal Python"
Also, it's cumbersome to write the text string and then parse it as JSON. Just use a JavaScript object.
You're also making it difficult on yourself when trying to determine the animal. Use Array.findIndex() if your browser supports it.
Here's a working example:
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>

Related

Is it possible to use a for loop to display values using buttons?

Hello here is my code at the moment. I would like to be able to display "you have selected" and then the name of the player that you pressed the draft button with however when pressing the button then it says you have selected "undefined". Would anyone be able to help thank you very much
var players=["Patrick Mahomes",
"Tyreek Hill",
"Travis Kelce",
"Chris Jones",
"Tom Brady"];
len=players.length;
for (var i=1;
i < len;
i++) {
document.getElementById("draft").innerHTML+=players[i]+"<button type=\"button\" onclick=\"draft()\">Draft</button><br>"
}
function draft() {
document.getElementById("demo").innerHTML+="You have selected"+players[i]+"<br>";
players.splice(players[i]);
}
<p id="draft"></p>
<p id="demo"></p>
the problem is that you don't specify the index when calling draft. You have to call it with the current index. I modified your code for it to work.
It should be easy to understand.
I also changed your var to let as it is better practice in javascript
<script>
let players = ["Patrick Mahomes", "Tyreek Hill", "Travis Kelce", "Chris Jones", "Tom Brady"];
let len = players.length;
for (let i = 0; i < len; i++) {
document.getElementById("draft").innerHTML += players[i] + "<button type='button' onclick='draft("+i+")'>Draft</button><br>"
}
function draft(player) {
document.getElementById("demo").innerHTML += "You have selected " + players[player] + "<br>";
players.splice(players[player]);
}
</script>
yes you can pass the player name as arg for draft()
for (var i=1;i<len;i++) {
document.getElementById("draft").innerHTML+=players[i]+"<button type=\"button\" onclick=\"draft('"+players[i]+"')\">Draft</button><br>"
}
function draft(player){
document.getElementById("demo").innerHTML+="You have selected "+player+"<br>";
players.splice(players[i]);
}
Why not pass i
<!DOCTYPE html>
<html>
<head>
<title>
Draft
</title>
</head>
<body>
<p id="draft"></p>
<script>
var players=["Patrick Mahomes","Tyreek Hill","Travis Kelce","Chris Jones","Tom Brady"];
len=players.length;
for (var i=0;i<len;i++) {
document.getElementById("draft").innerHTML+=players[i]+"<button type=\"button\" onclick=\"draft("+i+")\">Draft</button><br>"
}
// use different variable name for function parameter as var has scope for i here
function draft(k){
document.getElementById("demo").innerHTML+="You have selected"+players[k]+"<br>";
players.splice(players[k]);
}
</script>
<p id="demo"></p>
</body>
</html>
I didn't test but should work. I don't know why you are using players.splice(players[i]); but if you want to remove the element from players use
players.splice(k, 1);
See more https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice#Syntax
Just pass the index to your method draft so you can use it to display the right cell from your array:
var players = ["Patrick Mahomes", "Tyreek Hill", "Travis Kelce", "Chris Jones", "Tom Brady"];
for (var i = 1; i < players.length; i++) {
document.querySelector("#draft").innerHTML += players[i] + "<button type=\"button\" onclick=\"draft("+i+")\">Draft</button><br>"
}
function draft(index) {
document.getElementById("demo").innerHTML += "You have selected " + players[index] + "<br>";
}
<p id="draft"></p>
<p id="demo"></p>
I think you made a typo at declaring the "len" var.
try to use "var len = players.length" or use a comma after the players var declaration.

Autocomplete with JSON

I have JSON data and I guess my JSON is works but there is something that I didn't understand how it's going to work ? when I wrote cities or countries nothing happend how will I make it work ?
I havedata-list attribute and when I clicked my input my data-list opening automatically it's ok so far.but if I wrote something my inline data-list attribute musn't work anymore only my Json must work how can I do that ?
I'm using Awesomplete plugin and if you want to see my project on codepen please click to see on codepen
var myJSON = '{ "cities":[ "copenhagen", "london", "hamburg" ], "countries":[ "denmark", "norway", "sweden" ] }';
var myObj = JSON.parse(myJSON);
document.getElementById("demo").innerHTML = "Cities : " + myObj.cities;
document.getElementById("demo1").innerHTML = "countries : " + myObj.countries;
function showlist() {
}
var comboplete = new Awesomplete('input.dropdown-input', {
minChars: 0,
});
Awesomplete.$('#test').addEventListener("click", function() {
if (comboplete.ul.childNodes.length === 0) {
comboplete.minChars = 0;
comboplete.evaluate();
} else if (comboplete.ul.hasAttribute('hidden')) {
comboplete.open();
} else {
comboplete.close();
}
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/awesomplete/1.1.1/awesomplete.min.css" rel="stylesheet" />
<div id="demo"></div>
<div id="demo1"></div>
<!--<input type="text" class="awesomplete" data-list="PHP,ASP,ASP.NET,Python,CSS,HTML,C#,C++,Delphi,Visual Basic" onclick="showlist()">-->
<br><br> with auto list
<input id="test" data-list="CSS, JavaScript, HTML, SVG, ARIA, MathML" class="dropdown-input" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/awesomplete/1.1.1/awesomplete.min.js"></script>
You have to access the attribute "data-list" of your input and set your json as data source.
Try this:
var testInput = document.getElementById("test");
testInput.setAttribute("data-list", myObj.countries)

Create Repeatable HTML Form and Load Info from a JS Array

I have a JS array with info in it. I want to populate some sort of repeatable object such that I can display all the info in the same way (formatted). I assumed I would need to use a HTML form, but now can't figure out how to exactly populate it with the information from my JS array. I want to make this happen on a page load, but for right now I am trying to test it with a button.
<html>
<head>
</head>
<body>
<script>
var myArray = [
{
"title" : "My First Place",
"address": "My First Address",
},
{
"title" : "Treehouse",
"address": "off in the woods",
},
{
"title" : "My New Place",
"address": "Home Sweet Home",
}
];
function addRow() {
var itm = document.getElementById("infoArea");
var cln = itm.cloneNode(true);
for(var i = 0; i < myArray.length; i++){
document.getElementById("repeatafterme").appendChild(cln);
}
}
</script>
<div id="repeatafterme"></div>
<form name="myform" id="infoArea">
<fieldset>
<legend><label id="myFormID"><output name="title"></output><label></legend>
<label><output name="address"></output></label>
</fieldset>
</form>
<INPUT TYPE="button" NAME="myButton" VALUE="Press This" onclick="addRow()">
</body>
</html>
itm.cloneNode(true) must be within the block for and set different id to element new.
To set value of array title and address should access to children for get elements out
function addRow() {
var itm = document.getElementById("infoArea");
for(var i = 0; i < myArray.length; i++){
var cln = itm.cloneNode(true);
cln.id = "id" + i;
var outTitle = cln.childNodes[1].childNodes[1].childNodes[0].childNodes[0];
outTitle.value = myArray[i].title;
var outAddress = cln.childNodes[1].childNodes[3].childNodes[0];
outAddress.value = myArray[i].address;
document.getElementById("repeatafterme").appendChild(cln);
}
}
result: https://jsfiddle.net/cmedina/sL0v07tt/1/

appendChild usage, variable array Javascript

trying to use appendChild to create a child element in a paragraph, I think I'm missing something fundamental here but I can't figure out what and not sure I'm using appendChild correctly.
<!DOCTYPE html>
<html>
<body>
<p>Accessing Variables from an Array</p>
<p id="demo"></p>
<script>
var employees = [
{
"firstName":"John",
"lastName":"Doe"
},
{
"firstName":"Anna",
"lastName":"Smith"
},
{
"firstName":"Peter",
"lastName":"Jones"
}
];
document.getElementById("demo").innerHTML =
employees[0].firstName + " " + employees[0].lastName;
childtest=document.getElementById("demo").innerHTML=employees[1].firstName;
first = document.getElementById("demo");
first.appendChild(childtest);
</script>
</body>
</html>
What I'm trying to do is create a child of "demo" and take the second array of employees and make that the child element and output that underneath the first output.
childtest is not a element here.
// Create a new empty <p> element.
var childtest = document.createElement('p');
// Set the innerHTML.
childtest.innerHTML = employees[1].firstname;
// Append that <p> element.
first.appendChild(childtest);
your problem is that you're not creating a new element and with .innerHTML you're just overwriting existing
fiddle
var employees = [{
"firstName": "John",
"lastName": "Doe"
}, {
"firstName": "Anna",
"lastName": "Smith"
}, {
"firstName": "Peter",
"lastName": "Jones"
}];
document.getElementById("demo").innerHTML = employees[0].firstName + " " + employees[0].lastName;
var newEl = document.createTextNode(employees[1].firstName);
first = document.getElementById("demo");
first.appendChild(newEl);
Katpoes got it right, just for clarification, this works:
<!DOCTYPE html>
<html>
<body>
<p>How to create a JavaScript object array.</p>
<p id="demo"></p>
<script>
var employees = [
{
"firstName":"John",
"lastName":"Doe"
},
{
"firstName":"Anna",
"lastName":"Smith"
},
{
"firstName":"Peter",
"lastName":"Jones"
}
];
document.getElementById("demo").innerHTML =
employees[0].firstName + " " + employees[0].lastName;
var childtest=document.createElement("p");
childtest.innerHTML = employees[1].firstName;
first = document.getElementById("demo");
first.appendChild(childtest);
</script>
</body>
</html>

Find an element in a JSON file and show it in HTML

I have the following JSON file
{
"agenti":[
{"codice":"3425", "nome":"fabrizio", "cognome":"mazzeini", "azienda":"kra", "indirizzo": {"via":"via milano", "citta":"Roma","stato":"Italia"}},
{"codice":"3476", "nome":"marco", "cognome":"sormani", "azienda":"bertucci", "indirizzo": {"via":"via Siena", "citta":"Milano" , "stato":"Italia"}},
{"codice":"4525", "nome":"francesco", "cognome":"stefanucci", "azienda":"ovs", "indirizzo": {"via":"via italia", "citta":"Milano" , "stato":"Italia"}},
{"codice":"3405", "nome":"emilio", "cognome":"emiglietti", "azienda":"paoletti", "indirizzo": {"via":"via delle forze armate", "citta":"Milano" , "stato":"Italia"}},
{"codice":"3915", "nome":"gianni", "cognome":"sperti", "azienda":"giacomazzi", "indirizzo": {"via":"via quarenghi", "citta":"Milano" , "stato":"Italia"}},
{"codice":"3429", "nome":"franca", "cognome":"solari", "azienda":"apple", "indirizzo": {"via":"via dei missaglia", "citta":"Milano" , "stato":"Italia"}}
]}
And the following HTML/JS file
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<body>
<h1>JSON</h1>
<button id="es" type="button" onclick="testJSON()"> UPLOAD JSON </button>
Search for agenti per <br> <br>
Nome<input type="text" id="nome"> <br><br>
<button type="button" id="filtra" onclick="filter()"> Filter </button>
<p id="demo"> </p>
<script>
var agenti = "";
function testJSON()
{
var successo = function(result) {
console.log("success");
console.log(result);
agenti = result;
};
var error = function (error) {
console.log(error);
};
$.ajax ({
dataType: "json",
url: "agenti.json",
success: successo,
error: error
});
var a = 10;
}
</script>
<script>
function filter() {
var name = document.getElementById("nome").value;
for (var i=0; i < agenti.length; i++) {
if (agenti[i].nome === nome) {
document.getElementById("demo").innerHTML = name;
}
}
}
</script>
</body>
</html>
I fill the input box with "fabrizio" for example... But HTML does not return any value and does not print "fabrizio" as a found element in the JSON file...
But if i do something like that:
<script>
var name = document.getElementById("nome").value;
document.getElementById("demo").innerHTML = name;
function filter() {
for (var i=0; i < agenti.length; i++) {
if (agenti[i].nome === nome) {
}
}
}
</script>
and i fill in the input box with a casual name, HTML returns the name in the document (and prints it) even if is not present in the JSON file
I guess the problem is in the for loop and precisely in the if conditional
What can i do ? Thanks to everybody
you have :
agenti = result;
so within that data structure you must go to :
agenti.agenti[0].nome
to get your result. agenti is set to the entire encapsulating object and you want the first object, agenti, within that. I would obviously change your variable to something less confusing.
You made two mistakes there. First of all mixing up JSON object keys with Javascript variables which apparently led to confusion. Also, like Mark pointed out, you have wrapped the result in the variable agenti. I made a JSFiddle where all things are working. If you have more questions feel free to comment. What you do is basically:
var name = document.getElementById("nome").value;
for (var i = 0; i < agenti.agenti.length; i++) {
if (agenti.agenti[i].nome === name) {
document.getElementById("demo").innerHTML = agenti.agenti[i].nome + ' & ' + agenti.agenti[i].codice;
}
}
OLD ANSWER
The variable "nome" is not declared, "name" is.
if (agenti[i].nome === name) {}
"nome" is a typo you made in the JSON file and the HTML DOM, I guess. You should correct that.
Also, you don't have to create two script tags for two functions. Just put both of them into the first script tag.

Categories