I am working on Address book using HTML,CSS and Javascript. First I am reading some data entries from a JSON file. Then storing those entries into local storage. Then I am taking input from the user in few input fields through the function called addToBook(). And then storing all the data in JSON format in the variable called addressBook. But when i am trying to print this data in the function called showaddressBook(). It is not happening as it is showing as Undefined in the chrome console. Refer to this line(console.log(addressBook[i].practice_name);) in the function showaddressBook(). Any idea guys. Thanks in advance.
window.onload = function(){
var quickAddFormDiv = document.querySelector('.quickaddForm');
var AddBtn = document.getElementById('Add');
// Form Fields
var lastname = document.getElementById('lastname');
var firstname = document.getElementById('firstname');
var email = document.getElementById('email');
var specialty = document.getElementById('specialty');
var practicename = document.getElementById('practicename');
// Divs etc.
var addBookDiv = document.querySelector('.addbook');
var addressBook = [];
var people;
localStorage.clear();
//--------------------------------------------------------------------
//To display the contents of JSON file
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var response = JSON.parse(xhttp.responseText);
people = response.people;
//var output = "";
var str1 = '';
for(var i = 0; i <people.length;i++){
str1 += '<div id="entry">';
str1 += '<div id="name"><p>' + people[i].last_name +', '+people[i].first_name+ '</p></div>';
str1 += '<div id="email"><p>' + people[i].email_address + '</p></div>';
str1 += '<div id="practicename"><p>' + people[i].practice_name + '</p></div>';
str1 += '<div id="specialty"><p>' + people[i].specialty + '</p></div>';
str1 += '<div id="del">Delete</div>';
}
for(var i = 0; i < people.length;i++){
var obj = new jsonStructure(people[i].last_name,people[i].first_name,people[i].email_address,people[i].specialty,people[i].practice_name);
addressBook.push(obj);
localStorage['addbook'] = JSON.stringify(addressBook);
}
document.getElementsByClassName("addbook")[0].innerHTML = str1;
}
};
xhttp.open("GET", "people.json", true);
xhttp.send();
//------------------------------------------------------------------------------
AddBtn.addEventListener("click", addToBook);
//var addressBook = [];
addBookDiv.addEventListener("click", removeEntry);
function jsonStructure(lastname,firstname,email,specialty,practicename){
this.lastname = lastname;
this.lastname += ", "+firstname;
this.email = email;
this.specialty = specialty;
this.practicename = practicename;
}
function addToBook(){
var isNull = lastname.value!='' && firstname.value!='' && email.value!='' && specialty.value!='' && practicename.value!='';
if(isNull){
// format the input into a valid JSON structure
var obj = new jsonStructure(lastname.value,firstname.value,email.value,specialty.value,practicename.value);
addressBook.push(obj);
localStorage['addbook'] = JSON.stringify(addressBook);
console.log(localStorage['addbook']);
clearForm();
showaddressBook();
}
}
function removeEntry(e){
// Remove an entry from the addressBook
if(e.target.classList.contains('delbutton')){
var remID = e.target.getAttribute('data-id');
addressBook.splice(remID,1);
localStorage['addbook'] = JSON.stringify(addressBook);
showaddressBook();
}
}
function clearForm(){
var formFields = document.querySelectorAll('.formFields');
for(var i in formFields){
formFields[i].value = '';
}
}
function showaddressBook(){
if(localStorage['addbook'] === undefined){
localStorage['addbook'] = '';
} else {
addressBook = JSON.parse(localStorage['addbook']);
addBookDiv.innerHTML = '';
var str = '';
for(var i = 0; i <addressBook.length;i++){
str += '<div id="entry">';
str += '<div id="name"><p>' + addressBook[i].last_name +', '+addressBook[i].first_name+ '</p></div>';
str += '<div id="email"><p>' + addressBook[i].email_address + '</p></div>';
str += '<div id="practicename"><p>' + addressBook[i].practice_name + '</p></div>';
str += '<div id="specialty"><p>' + addressBook[i].specialty + '</p></div>';
str += '<div id="del">Delete</div>';
console.log(addressBook[i].practice_name);
}
}
}
showaddressBook();
}
There are typo mistakes,
practice_name should be practicename
last_name should be lastname
first_name should be firstname
email_address should be email
Try:
for(var i = 0; i <addressBook.length;i++){
str += '<div id="entry">';
str += '<div id="name"><p>' + addressBook[i].lastname +', '+addressBook[i].firstname+ '</p></div>';
str += '<div id="email"><p>' + addressBook[i].email + '</p></div>';
str += '<div id="practicename"><p>' + addressBook[i].practicename + '</p></div>';
str += '<div id="specialty"><p>' + addressBook[i].specialty + '</p></div>';
str += '<div id="del">Delete</div>';
console.log(addressBook[i].practicename);
}
Related
I'm trying to pull thumbnail URLs from a wordpress feed and keep getting [object HTMLCollection] instead of an image URL string for the thumbnail. The feed i'm pulling from is: https://harpercollegece.com/feed/. I know that the tag is named media:thumbnail and the value is stored in 'URL'. I can't find the correct way to reference this image inside of the forEach loop when running through each post. I've tried searching other posts as well as on google for several hours.
var proxy = 'https://api.allorigins.win/raw?url=';
var feeds = [
'https://harpercollegece.com/feed/',
];
var limit = 10;
var forEach = function (array, callback, scope) {
for (var i = 0; i < array.length; i++) {
callback.call(scope, i, array[i]);
}
};
function strip_tags(string) {
if ((string === null) || (string === '')) {
return '';
} else {
string = string.toString();
}
string = string.replace('<![CDATA[', '');
string = string.replace(' […]]]>', '');
string = string.replace(/<[^>]*>/g, '');
string = string.replace(/<[^>]*>/g, '');
string = string.replace(']]>', '');
return string;
}
function get_rss(url) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState !== 4) {
return;
}
if (xhr.status >= 200 && xhr.status < 300) {
var response = xhr.responseText;
var parser = new window.DOMParser();
var data = parser.parseFromString(response, "text/xml");
var items = Array.from(data.querySelectorAll("item"));
var output = '';
forEach(items, function(index, item) {
if (index <= limit) {
var ilink = item.querySelector("link").innerHTML;
var title = item.querySelector("title").innerHTML;
var descr = item.querySelector("description").innerHTML;
var thumb = item.getElementsByTagName("media:thumbnail");
//console.log(item);
output +=
'<div class="ce-blog-slider-well">' +
'<div class = "ce-blog-thumb">' +
'<img class="blog-post-img" src="' + thumb + '" alt="Veterans Center Sign">' +
'</div>' +
'<div class = "ce-blog-header">' +
'' + strip_tags(title) + '' +
'</div>' +
'<div class ="ce-blog-descr">' + strip_tags(descr) + '</div>' +
'</div>';
}
});
var d1 = document.getElementById('wp-blog-posts');
d1.insertAdjacentHTML("beforeend", output);
}
};
xhr.open('GET', url);
xhr.send();
}
forEach(feeds, function(index, feed) {
get_rss(proxy + encodeURIComponent(feed));
});
<div class="ce-blog-slider" id="wp-blog-posts"></div>
getElementsByTagName returns an HTMLCollection. To get the URL, you'll have to grab the first element in that collection with [0]. The URL is stored in an attribute called url, a la
<media:thumbnail url="https://harpercollegece.files.wordpress.com/2021/01/writing-red-typewriter-typing.jpg" />
From your HTMLElement, get the url attribute like so:
var thumb = item.getElementsByTagName("media:thumbnail")[0].getAttribute("url");
var proxy = 'https://api.allorigins.win/raw?url=';
var feeds = [
'https://harpercollegece.com/feed/',
];
var limit = 10;
var forEach = function (array, callback, scope) {
for (var i = 0; i < array.length; i++) {
callback.call(scope, i, array[i]);
}
};
function strip_tags(string) {
if ((string === null) || (string === '')) {
return '';
} else {
string = string.toString();
}
string = string.replace('<![CDATA[', '');
string = string.replace(' […]]]>', '');
string = string.replace(/<[^>]*>/g, '');
string = string.replace(/<[^>]*>/g, '');
string = string.replace(']]>', '');
return string;
}
function get_rss(url) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState !== 4) {
return;
}
if (xhr.status >= 200 && xhr.status < 300) {
var response = xhr.responseText;
var parser = new window.DOMParser();
var data = parser.parseFromString(response, "text/xml");
var items = Array.from(data.querySelectorAll("item"));
var output = '';
forEach(items, function(index, item) {
if (index <= limit) {
var ilink = item.querySelector("link").innerHTML;
var title = item.querySelector("title").innerHTML;
var descr = item.querySelector("description").innerHTML;
var thumb = item.getElementsByTagName("media:thumbnail")[0].getAttribute("url");
//console.log(item);
output +=
'<div class="ce-blog-slider-well">' +
'<div class = "ce-blog-thumb">' +
'<img class="blog-post-img" src="' + thumb + '" alt="Veterans Center Sign">' +
'</div>' +
'<div class = "ce-blog-header">' +
'' + strip_tags(title) + '' +
'</div>' +
'<div class ="ce-blog-descr">' + strip_tags(descr) + '</div>' +
'</div>';
}
});
var d1 = document.getElementById('wp-blog-posts');
d1.insertAdjacentHTML("beforeend", output);
}
};
xhr.open('GET', url);
xhr.send();
}
forEach(feeds, function(index, feed) {
get_rss(proxy + encodeURIComponent(feed));
});
<div class="ce-blog-slider" id="wp-blog-posts"></div>
How do i show all the data by using the loop to display all the data from json to html ?
ATM , I am able to print one of the data. but if i am using data[i] the code will not display any data.
I think I mess up the the concept of object and array.
please advice me , how to loop thru object , like array?
thanks
var getWeather = document.getElementById('weather');
var requestWeather = new XMLHttpRequest();
//+'-31' +'&lon='+'150'
requestWeather.open('GET','https://fcc-weather-api.glitch.me/api/current?lat=-31&lon=150');
requestWeather.onload = function () {
var weatherData = JSON.parse(requestWeather.responseText);
console.log(weatherData);
getHTML(weatherData);
};
requestWeather.send();
function getHTML(data) {
var weatherString = "";
for(var i in data.weather ){
var x= data.weather[i].main;
weatherString+= "<p class='weather'>" + x + "</p>";
// weatherString+= "<p>" + data.currently.summary + "</p>";
// console.log(data[i].city);
}
getWeather.insertAdjacentHTML("beforeend", weatherString);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="weather"></div>
to get all data check for object and do recursive loop
var getWeather = document.getElementById('weather');
var requestWeather = new XMLHttpRequest();
//+'-31' +'&lon='+'150'
requestWeather.open('GET', 'https://fcc-weather-api.glitch.me/api/current?lat=-31&lon=150');
requestWeather.onload = function() {
var weatherData = JSON.parse(requestWeather.responseText);
//console.log(weatherData);
getHTML(weatherData);
};
requestWeather.send();
function getHTML(data) {
var weatherString = "";
for(var i in data) {
var x = data[i];
if(typeof(x) == "object") {
getHTML(x);
}
else {
weatherString += "<p class='weather'><b>" + i + "</b>: " + x + "</p>";
// weatherString+= "<p>" + data.currently.summary + "</p>";
// console.log(data[i].city);
}
}
getWeather.insertAdjacentHTML("beforeend", weatherString);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="weather"></div>
var getWeather = document.getElementById('weather');
var requestWeather = new XMLHttpRequest();
//+'-31' +'&lon='+'150'
requestWeather.open('GET', 'https://fcc-weather-api.glitch.me/api/current?lat=-31&lon=150');
requestWeather.onload = function() {
var weatherData = JSON.parse(requestWeather.responseText);
getHTML(weatherData);
};
requestWeather.send();
function getHTML(data) {
var weatherString = "";
for (var i in data.weather) {
var x = data.weather[i].main;
weatherString += "<p class='weather'>" + x + "</p>";
$.each(data.main, function(i, f) {
var main = "<div>" + i + ": " + f + "</div>";
$(main).appendTo("#main");
});
}
getWeather.insertAdjacentHTML("beforeend", weatherString);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="weather"></div>
<div id="main"></div>
use foreach loop to iterate over all object
read more from here
I was trying to make something where you can type a string, and the js only shows the objects containing this string. For example, I type Address1 and it searches the address value of each one then shows it (here: it would be Name1). Here is my code https://jsfiddle.net/76e40vqg/11/
HTML
<input>
<div id="output"></div>
JS
var data = [{"image":"http://www.w3schools.com/css/img_fjords.jpg","name":"Name1","address":"Address1","rate":"4.4"},
{"image":"http://shushi168.com/data/out/114/38247214-image.png","name":"Name2","address":"Address2","rate":"3.3"},
{"image":"http://www.menucool.com/slider/jsImgSlider/images/image-slider-2.jpg","name":"Name3","address":"Address3","rate":"3.3"}
];
var restoName = [], restoAddress = [], restoRate = [], restoImage= [];
for(i = 0; i < data.length; i++){
restoName.push(data[i].name);
restoAddress.push(data[i].address);
restoRate.push(data[i].rate);
restoImage.push(data[i].image);
}
for(i = 0; i < restoName.length; i++){
document.getElementById('output').innerHTML += "Image : <a href='" + restoImage[i] + "'><div class='thumb' style='background-image:" + 'url("' + restoImage[i] + '");' + "'></div></a><br>" + "Name : " + restoName[i] + "<br>" + "Address : " + restoAddress[i] + "<br>" + "Rate : " + restoRate[i] + "<br>" + i + "<br><hr>";
}
I really tried many things but nothing is working, this is why I am asking here...
Don't store the details as separate arrays. Instead, use a structure similar to the data object returned.
for(i = 0; i < data.length; i++){
if (data[i].address.indexOf(searchedAddress) !== -1) { // Get searchedAddress from user
document.getElementById("output").innerHTML += data[i].name;
}
}
Edits on your JSFiddle: https://jsfiddle.net/76e40vqg/17/
Cheers!
Here is a working solution :
var data = [{"image":"http://www.w3schools.com/css/img_fjords.jpg","name":"Name1","address":"Address1","rate":"4.4"},
{"image":"http://shushi168.com/data/out/114/38247214-image.png","name":"Name2","address":"Address2","rate":"3.3"},
{"image":"http://www.menucool.com/slider/jsImgSlider/images/image-slider-2.jpg","name":"Name3","address":"Address3","rate":"3.3"}
];
document.getElementById('search').onkeyup = search;
var output = document.getElementById('output');
function search(event) {
var value = event.target.value;
output.innerHTML = '';
data.forEach(function(item) {
var found = false;
Object.keys(item).forEach(function(val) {
if(item[val].indexOf(value) > -1) found = true;
});
if(found) {
// ouput your data
var div = document.createElement('div');
div.innerHTML = item.name
output.appendChild(div);
}
});
return true;
}
<input type="search" id="search" />
<div id="output"></div>
I am trying to rebuild an old application without the loss of data. The current data has all been stored in xml files that i am trying to read using Javascript.
This is the Javascript (i'm new to this, feedback is appreciated):
// Create a connection to the file.
var Connect = new XMLHttpRequest();
// Define which file to open and
// send the request.
Connect.open("GET", "writers.xml", false);
Connect.setRequestHeader("Content-Type", "text/xml");
Connect.send(null);
// Place the response in an XML document.
var TheDocument = Connect.responseXML;
// Place the root node in an element.
var Customers = TheDocument.childNodes[0];
// Retrieve each customer in turn.
for (var i = 0; i < Customers.children.length; i++){
var Customer = Customers.children[i];
//Create div's for data
document.getElementById("body").innerHTML += "<div id='who" + i + "'></div>"
document.getElementById("body").innerHTML += "<div id='age" + i + "'></div>"
document.getElementById("body").innerHTML += "<div id='hobby" + i + "'></div>"
document.getElementById("body").innerHTML += "<div id='image" + i + "'></div>"
document.getElementById("body").innerHTML += "<div id='something" + i + "'></div>"
//Assign data to correct divs
var who = Customer.getElementsByTagName("name");
var who2 = who[0].textContent.toString();
document.getElementById("who"+i).innerHTML += who2;
var age = Customer.getElementsByTagName("age");
var age2 = age[0].textContent.toString();
document.getElementById("age"+i).innerHTML += age2;
var hobby = Customer.getElementsByTagName("hobby");
var hobby2 = hobby[0].textContent.toString();
document.getElementById("hobby"+i).innerHTML += hobby2;
var image = Customer.getElementsByTagName("image");
var image2 = image[0].textContent.toString();
document.getElementById("image"+i).innerHTML += image2;
var something = Customer.getElementsByTagName("something");
var something2 = something[0].textContent.toString();
document.getElementById("something"+i).innerHTML += something2;
}
This is an example of my xml file:
<doc>
<person>
<name>Paul</name>
<age>21</age>
<hobby>blabla</hobby>
<image>thisisanimage.jpg</image>
<something>Random string</something>
</person>
<person>
<name>Peter</name>
<age></age>
<hobby>blabla</hobby>
<image>thisisanimage.jpg</image>
<something>Random string</something>
</person>
</doc>
Now i am trying to filter Peter out, because the age field is empty. Anyone got an idea?
The easiest way is to add a condition in the loop, to test if the age is blank. If the age value is blank then the if block will not be entered, and the next iteration of the loop will start.
for (var i = 0; i < Customers.children.length; i++) {
var Customer = Customers.children[i];
var age = Customer.getElementsByTagName("age");
var age2 = age[0].textContent.toString();
if (age2 != '') { // only do the below code if age2 is not blank
//Create div's for data
document.getElementById("body").innerHTML += "<div id='who" + i + "'></div>"
document.getElementById("body").innerHTML += "<div id='age" + i + "'></div>"
document.getElementById("body").innerHTML += "<div id='hobby" + i + "'></div>"
document.getElementById("body").innerHTML += "<div id='image" + i + "'></div>"
document.getElementById("body").innerHTML += "<div id='something" + i + "'></div>"
document.getElementById("age" + i).innerHTML += age2;
//Assign data to correct divs
var who = Customer.getElementsByTagName("name");
var who2 = who[0].textContent.toString();
document.getElementById("who" + i).innerHTML += who2;
var hobby = Customer.getElementsByTagName("hobby");
var hobby2 = hobby[0].textContent.toString();
document.getElementById("hobby" + i).innerHTML += hobby2;
var image = Customer.getElementsByTagName("image");
var image2 = image[0].textContent.toString();
document.getElementById("image" + i).innerHTML += image2;
var something = Customer.getElementsByTagName("something");
var something2 = something[0].textContent.toString();
document.getElementById("something" + i).innerHTML += something2;
}
}
I have a two part question. The first is that I tried to replace all of my document.write with innerHTML and now nothing generates on the page correctly. The second part of my question is that I can't figure out the logic on my toggleCurrent function so that I can hide show the currently displayed view. example - if the thumbnail view is visible I want to hide/show or if the full view is visible I want to hide/show that. http://jsfiddle.net/5M3k7/
//Creating generic Object
function Person(name,age,biog,thumb,char,bg,cider) {
this.fullName = name;
this.age = age;
this.biog = biog;
this.thumb = thumb;
this.char = char;
this.bg = bg;
this.cider = cider;
}
//Creating new Objects
var jay = new Person ("Jay Jones",24,"Story","img","guy","bg","Fleet",true);
var jai = new Person ("Jai Janes",23,"Story","img","gal","bg","Sleet",true);
var dan = new Person ("Dan Dones",19,"Story","img","guy","bg","Leet",true);
var den = new Person ("Den Danes",49,"Story","img","guy","bg","Treat",true);
var dun = new Person ("Dun Dunes",20,"Story","img","guy","bg","Meet",true);
var vim = new Person ("Vim Vanes",22,"Story","img","guy","bg","Meat",true);
//Defining arrays
var characters = [jay, jai, dan, den, dun, vim];
//For loop goes though character array and prints it out.
var thumbs = function() {
var full = document.getElementById('full');
var cLength = characters.length;
for (var i = 0; i < cLength; i++){
full.innerHTML = '<div class="wrap"><div class="cont">' + "Name: " + characters[i].fullName + '<br/>' + 'Age: ' + characters[i].age + '<br/>' + 'Cider: ' + characters[i].cider + '</div></div>';
}
return;
};
var full = function() {
var thumb = document.getElementById('fullthumb');
var cLength = characters.length;
for (var i = 0; i < cLength; i++){
thumb.innerHTML = '<div class="fullwrap"><div class="bg"><div class="fullcont">Name: '
+ characters[i].fullName + '<br/> Age:' + characters[i].age + '<br/>Cider:' + characters[i].cider + '<div class="char"></div></div></div></div>';
}
return;
};
//Toggle Function
function toggleMenuDiv() {
var full = document.getElementById('full');
var thumb = document.getElementById('fullthumb');
var butt = document.getElementById('button');
if (full.style.display == 'none') {
full.style.display = 'block';
thumb.style.display = 'none';
butt.innerHTML = 'THUMB VIEW<span class="arrow-e"></span>';
}
else {
full.style.display = 'none';
thumb.style.display = 'block';
butt.innerHTML = 'FULL VIEW<span class="arrow-e"></span>';
}
}
//Toggle Function
function toggleCurrent() {
var chng = document.getElementById('change');
var thumb = document.getElementById('fullthumb');
var full = document.getElementById('full');
while (full.style.display == 'none')
{
if(thumb.style.display == 'block') {
chng.innerHTML = 'HIDE<span class="arrow-n"></span>';
}else{
thumb.style.display = 'none';
chng.innerHTML = 'SHOW<span class="arrow-s"></span>';
}
}
}
Because you keep overriding the last thing entered in.
full.innerHTML = '<div class="wrap"><div class="cont">' + "Name: " + characters[i].fullName + '<br/>' + 'Age: ' + characters[i].age + '<br/>' + 'Cider: ' + characters[i].cider + '</div></div>';
You are need to append to the innerHTML
full.innerHTML = full.innerHTML + '<div class="...