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

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.

Related

How to display array elements passed into Handlebars file one by one on button click?

Suppose, I have following array of objects successfully sent to handlebars file from my express server:
[
{
"name": "Jon",
"isPositive": true
},
{
"name": "Cercei",
"isPositive": false
}
]
Each time when my button gets clicked, I want to show next element of the array on my view. Is it possible with handlebars? Or do I need something more complex like Vue.js to solve this problem? Here is simple pseudocode I would like to achieve:
<head>
<script>
$(document).ready(() => {
var index = 0;
var currentCharacter = getCurrentCharacter();
start();
});
</script>
</head>
<body>
<h3 id="name"></h3>
<p id="someInfo"> </p>
<button onclick="next()">Next</button>
<script>
function getCurrentCharacter() {
/// somehow access array of objects sent from server
var myCharacters = {{characters}}; // {} used because of handlebars
var character = myCharacters[index];
index += 1;
return character;
}
function start() {
document.getElementById("name").textContent = currentCharacter.name;
/// as you see here, I change my UI based on current object fields/attributes
if (currentCharacter.isPositive) {
document.getElementById("someInfo").style.display = "block";
document.getElementById("someInfo").textContent = "Some text here";
} else {
document.getElementById("someInfo").style.visibility = "hidden";
}
}
function next() {
currentCharacter = getCurrentCharacter();
start();
}
</script>
</body>
Is it possible to have such a logic with handlebars or other templating languages? If they are not build for these purposes, please recommend me another way to solve this problem.

Trying to loop through items in an object that are named strIngredients 1-15

event.preventDefault();
$('#mainContent').empty();
$.ajax({
url: randomDrinksURL,
method: 'GET'
}).then(function (response) {
console.log(response);
var mainContent = $('#mainContent');
mainContent.append(`
<img src='${response.drinks[0].strDrinkThumb}'>
<p>${response.drinks[0].strDrink}</p>
<p>${response.drinks[0].strMeasure1} of ${response.drinks[0].strIngredient1}</p>
<p> ${response.drinks[0].strInstructions}</p>
`);
});
The object lists all the ingredients and measurements from 1 - 15 and I am trying to find a way to go through them without having to write each one individually but it also needs to be able to know when to stop if the value is = null
I tried some sort of for loop and could not get that to work to save my life. any help would be great!
would something like this do the thing ?
let html = `
<img src='${response.drinks[0].strDrinkThumb}'>
<p>${response.drinks[0].strDrink}</p>
`
for (var i = 1; i<= 15; i++) {
let ingredient= "strIngredient" + i;
let measure= "strMeasure" + i;
if (response.drinks[0][measure] && response.drinks[0][ingredient]) {
html += `<p>${response.drinks[0][measure]} of ${response.drinks[0][ingredient]}</p>`
}
}
html += `<p> ${response.drinks[0].strInstructions}</p>`
mainContent.append(html)
edited
added null condition

Real time Javascript filtering not working throws undefined [duplicate]

This question already exists:
My live string search always returns false when it tries to match with includes() [duplicate]
Closed 3 years ago.
I want the code to return items from the JSON when i write something in the search bar (getting data from JSON tested and working).
The code is supposed to go to the JSON, read the line of the JSON (object) and compare with the keyword to see if it contains the keyword. If it contains it will display in <li> the item. It is always throwing "undefined".
<html>
<head>
<link href="https://fonts.googleapis.com/css?family=Roboto&display=swap" rel="stylesheet">
</head>
<body>
<input type="text" placeholder="Search Users" id="filter_items"/>
<ul id="items-list">
</ul>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
var json = (function() {
var json = null;
$.ajax({
'async': false,
'global': false,
'crossDomain': true,
'method': "get",
'url': "products.json",
'dataType': "json",
'success': function (data) {
json = data;
}
});
return json;
})();
// lets filters it
ul = document.getElementById("items-list");
input = document.getElementById('filter_items');
var filterItems = function(event, json){
keyword = input.value.toLowerCase();
var li = "";
for (var index in json)
{
for (var j in json[index])
{
var line = json[index][j];
var filtered_items = line.title.filter(function(lin){
lin = lin.title.toLowerCase();
return lin.title.indexOf(keyword) > -1;
});
}
}
li += "<li>"+filtered_items+"</li>";
ul.innerHTML = li;
}
input.addEventListener('keyup', filterItems);
</script>
</body>
</html>
The JSON
{
"items": [{
"title": "Express"
}, {
"title": "Unexpress"
}]
}
It is supposed to return items matching the keyword in real time.
UPDATE
JSON isn't passing as parameter into the function with event as parameter too. Anyone know how to solve it?
You aren't passing an additional variable to the function when you trigger the event, so it's unclear why you'd expect json to be populated.
But you don't need it anyway - the content of JSON doesn't change every time the event happens, the data is always the same. Just download it when your page loads, and then add the event listener when it's finished downloading, and use the function without the additional parameter. json can be declared global so it'll be in scope.
I think the code might make more sense like this:
var json = null;
$.ajax({
'global': false,
'crossDomain': true,
'method': "get",
'url': "products.json",
'dataType': "json",
'success': function (data) {
json = data;
input.addEventListener('keyup', filterItems);
}
});
ul = document.getElementById("items-list");
input = document.getElementById('filter_items');
var filterItems = function(event){
keyword = input.value.toLowerCase();
var li = "";
for (var index in json)
{
for (var j in json[index])
{
var line = json[index][j];
var filtered_items = line.title.filter(function(lin){
lin = lin.title.toLowerCase();
return lin.title.indexOf(keyword) > -1;
});
}
}
li += "<li>"+filtered_items+"</li>";
ul.innerHTML = li;
}
P.S. 'async': false is deprecated due to the poor user experience it creates (locking up the main browser UI during requests). Some browsers will issue a console warning when you try to use it. But there should be no need for it. You should aim to use callbacks/promises correctly instead. I removed it in my example above, and instead (for reliability) we don't add the event listener to the input box until the JSON download has completed. Hopefully it isn't too big a file.
P.P.S. If you ever find yourself swapping the static JSON file for a server-side script to retrive product data from a database, it would be advisable to change your code so that the filtering of data happens on the server - usually it's a lot more efficient to filter using a SQL query and return only the data which is truly needed, than to download everything and then filter it using JavaScript.
I belive the filtering part should be changed.
Maybe to something like the following?
var json = { "items": [{"title": "Express"}, { "title": "Unexpress"}] };
// lets filters it
ul = document.getElementById("items-list");
input = document.getElementById('filter_items');
var filterItems = (event) => {
keyword = input.value.toLowerCase();
var li = "";
var filtered_items = json.items.filter(function(lin){
return lin.title.toLowerCase() == keyword;
});
for ( var i in filtered_items ) {
li += "<li>"+filtered_items[i].title+"</li>";
}
ul.innerHTML = li;
}
input.addEventListener('keyup', filterItems);
<body>
<input type="text" placeholder="Search Users" id="filter_items"/>
<ul id="items-list">
</ul>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

Get value from a JSON file with multi dimensional array using jQuery $.getJSON method

I've been trying to fetch some values from a JSON file using the $.getJSON method. The first two loops are static so I wrote the below code to fetch the value of "layers.name". From the third loop, the data in the layers may or may not be available. How can I fetch the value of all "layers.name"presented in the JSON file
PS: The JSON file is an output generated from a software where the layer is presented
in this format
Here the code I've worked so far where I get the first two loop layers.
Html
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="test.js"></script>
</body>
Javscript
$.getJSON('https://api.myjson.com/bins/6atbz', function(data) {
var layer = data.layers.reverse()
for (i=0; i<layer.length; i ++){
name = data.layers[i].name
id= data.layers[i].do_objectID
var className = '.'+id
var main = "<div class=\""+id+"\" data-number=\""+i+"\">"+name+"<\/div>"
$('body').append(main);
var subLayer = data.layers[i].layers.reverse()
for(j=0; j<subLayer.length; j++){
newname = data.layers[i].layers[j].name
$().append(' '+newname);
var subsubLayer = data.layers[i].layers[j]
var sub = "<div class=\""+newname+"\" data-number=\""+j+"\">"+newname+"<\/div>"
$(className).append(sub);
}
}
})
Thanks
Link to Fiddle
I think it's a good idea use recursion. Here is example:
var container = document.getElementById("container");
$.getJSON('https://api.myjson.com/bins/6atbz', function(data) {
buildTree(data, container)
})
function buildTree (node, container) {
var layers = node.layers || [];
console.info(node);
layers.forEach(function(item) {
var newContainer = document.createElement('div');
var span = document.createElement('span');
span.innerHTML = item.name;
newContainer.appendChild(span);
container.appendChild(newContainer);
if(item.layers){
buildTree(item, newContainer)
}
});
}
Here is live demo

New to HTML5 and JavaScript, and I can't connect JavaScript file to HTML file?

So I am having a problem with HTML5 and javascript.
I made a few .js files for the javascript part and I made the link to connect it with the HMTL code but it will not show the javascript part.
This is my HTML
<!doctype html>
<html lang="en">
<head>
<title>Gateway Tunes</title>
<meta charset="utf-8" />
<script src="playlist_store.js"></script>
<script src="playlist.js"></script>
</head>
<body>
<form>
<input type="text" id="songTextInput" size="40" placeholder="Song name">
<input type="button" id="addButton" value="Add Song">
</form>
<ul id="playlist">
</ul>
</body>
</html>
and here are my javascript files; the names of the files are at the top
playlist_store.js
function save(item) {
var playlistArray = getStoreArray("playlist");
playlistArray.push(item);
localStorage.setItem("playlist", JSON.stringify (playlistArray));
}
function loadPlaylist() {
var playlistArray = getSavedSongs();
var ul = document.getElementById('playlist");
if (playlistArray !Null) {
for (var i = 0; i < playlistArray.length; i++) {
li.innerHTML = playlistArrray[i];
ul.appenChild(li);
}
}
}
function getSavedSongs() {
return getStoreArray("playlist")
}
function getStoreArray (key);
var playlistArray = localStorage.getItem(key);
if(playlistArray == null || playlistArray == "") {
playlistArray = new Array();
}
else {
playlistArray = JSON.parse (playlistArray);
}
return playlistArray;
}
playlist.js
window.onload = init;
function init() {
var button = document.getElementById ("addButton");
button.onclick = handleButtonClick;
loadPlaylist();
}
function handleButtonClick () {
var textInput = document.getElementById("songTextInput");
var songName = textInput.value;
if (songName == "") {
alert("Button was clicked!");
}
else {
alert("Your track has been added!");
}
var li = document.createElement("li");
li.innerHTML = songName;
var ul = document.getElementById("playlist");
ul.appendChild(li);
save (songName);
}
You've got some syntax errors so your javascript isn't running.
In playlist_store.js
var ul = document.getElementById('playlist");
Opens a string with ' but tries to close it with ". It doesn't matter which you use as long as you're consistent, so you can either change it to 'playlist' or "playlist".
if (playlistArray !Null) {
If you're trying to make sure playlistArray isn't null you can do
if (playlistArray != null) {
notice != as the comparison and null needs to be lowercase. If you want to make sure it isn't just undefined or null you can simply do if (!playlistArray).
ul.appenChild(li); needs to be ul.appendChild(li);.
I'm sure there's more, check over your code.
The first line of your script (and the only one that isn't just a function definition) is window.onload = init;. This means that after the page has loaded, your init function is called.
This function looks up the element with id addbutton, and then calls a method on the returned result. Since you don't have an element with this ID, there won't be any object returned, and so an exception will be thrown (something like "button is null or not an object", depending on your browser). This exception stops the method from executing further - and in particular, loadPlaylist() will not be called.
The moral of the story here though is pay attention to the JavaScript error console, especially while you're doing development! You browser will almost certainly have displayed a red exclamation mark icon or similar, which you could double-click to give you the name, message and location of the exception.
You really don't need to post your code listing on Stack Overflow to ask us what's wrong with it, when your browser is already capable of telling you exactly where the problem is.

Categories