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="...
Related
This is the js file. What im trying to do is create an onclick delete function when clicked on a particular row in html page. So far i can get the child key(nesting) but somehow the delete function throws error i.e career-delete.html:1 Uncaught ReferenceError: MCu9V4ypS is not defined
at HTMLButtonElement.onclick (career-delete.html:1).
userImagesRef1.once("value", function(snapshot) {
var val1, val2, val3;
var ParentKey = snapshot.key;
console.log("PK"+ParentKey);
snapshot.forEach(function(childSnapshot) {
childSnapshot.forEach(function(snap){
var childKey = snap.key;
console.log("CK" + childKey);
var Vacancy = snap.child("VacancyNumber").val();
console.log("VacancyNumber" + Vacancy);
// var NoticeNumber = snap.child("Service").val();
// var NameofWork = snap.child("Title").val();
snap.child('pictures').forEach(function(openPicturesSnap){
console.log("KEY LINKS: " + openPicturesSnap.key);
// var i = 0;
if(openPicturesSnap.key == 0){
val1 = openPicturesSnap.val();
// console.log("LINKS1111::::" + val1 );
}
if(openPicturesSnap.key == 1){
val2 = openPicturesSnap.val();
}
if(openPicturesSnap.key == 3){
val1 = openPicturesSnap.val();
}
})
var Service = String(snap.child("Service").val());
// console.log(Service)
var ts = snap.child("timestamp").val();
// console.log("TS:" + ts);
var Title = String(snap.child("Title").val());
// console.log(Title)
let Numberofposts = String(snap.child("NumberofPosts").val());
// console.log(Numberofposts);
var SNo = "";
var State = snap.child("Status").val();
var IssueDate = snap.child("IssueDate").val();
var ClosingDate = snap.child("ClosingDate").val();
var Remarks = String(snap.child("Remarks").val());
$("#tableBody").append("<tr><td>"+ SNo +"</td><td><a href = '" + val1+ "'>" +Vacancy+"</a></td>"+ "<td><a href = '" +val2 + "'>" +Service+"</a></td><td>" + Title + "</td><td>"+Numberofposts+"</td><td>" + IssueDate + "</td><td>"+ClosingDate + "</td> <td>" + State+"<td><a href = '" +val3 + "'>" +Remarks+"</a>"+ "</td><td>"+'<button type="button" onClick=Delete('+childKey+'); class="btn delete">X</button>'+"</td></tr>" );
})
})
function Delete(key){
var feedRef = firebase.database().ref("user-images").child(key);
feedRef.remove()
.then(function(){
console.log("Remove succeeded.")
alert("Added");
// console.log(key.val());
})
.catch(function(error){
console.log("Remove Failed!"+error.message)
});
}
});
You can delete nodes by using the following alternative:
feedRef.set(null);
https://firebase.google.com/docs/database/web/read-and-write#delete_data
You need to add some double quotes as follows:
<button type="button" onclick="Delete('" +childKey+ "');" class="btn delete">X</button>
How do I remove just the current instance of the array, not all instances of the array?
var persons = [];
showAllButton.onclick = function() {
while (showList.firstChild)showList.removeChild(showList.firstChild);
Created new node instances.
for (var l in persons) {
var listNode = document.createElement("LI");
var btn = document.createElement("BUTTON");
btn.innerHTML = "Remove";
showList.appendChild(listNode);
showList.appendChild(btn);
Displays pushed instances correctly.
listNode.innerHTML =
'<p><b>Full Name:</b> ' + persons[l].firstName +' ' + persons[l].lastName + '</p>' +
'<p><b>Phone:</b> ' + persons[l].phone + '</p>' +
'<p><b>Address:</b> ' + persons[l].address + '</p>'
}
Tried a few variations of the following function but just empties the array, or at least wont return the amended array.
btn.onclick = function() {
var index = Array.indexOf(persons[l]);
persons.splice(index, 1);
return persons;
}
if (showAllButton.value=="Show Contacts") {
showAllButton.value = "Hide Contacts";
showList.style.display = "block";
}
else if (showAllButton.value = "Hide Contacts") {
showAllButton.value = "Show Contacts";
showList.style.display = "none";
}
}
probably bind l, remove the element at index l, then redraw the dom somehow.:
btn.onclick = function(l) { //take over the bound l
persons.splice(l, 1);
//some kind of redraw
showAllButton.click();
}.bind(null,l);//bind l
Something like this should work as expected (sorry, blind coding, have no time to test now)
var persons = [];
function removePerson(index) {
persons.splice(index, 1);
renderList();
}
function clearList() {
while (showList.firstChild) {
showList.removeChild(showList.firstChild);
}
}
function renderItem(person, index) {
var item = showList.appendChild(document.createElement("LI"));
var label = item.appendChild(document.createElement("SPAN"));
label.innerHTML = persons[i];
var btn = item.appendChild(document.createElement("BUTTON"));
btn.innerHRML = "Remove";
btn.onclick = removePerson.bind(null, index);
}
function renderList() {
clearList();
persons.forEach(renderItem);
}
Not a kind of best practices, but seems to be working.
Final Working Code, thank you!
showAllButton.onclick = function() {
while (showList.firstChild)showList.removeChild(showList.firstChild);
for (var l in persons) {
var list = showList.appendChild(document.createElement("LI"));
list.innerHTML =
'<p><b>Full Name:</b> ' + persons[l].firstName +' ' + persons[l].lastName + '</p>' +
'<p><b>Phone:</b> ' + persons[l].phone + '</p>' +
'<p><b>Address:</b> ' + persons[l].address + '</p>';
var btn = showList.appendChild(document.createElement("BUTTON"));
btn.innerHTML = "Remove";
btn.onclick = function(l) {
persons.splice(l, 1);
showAllButton.click();
}.bind(null,l);
}
I'm looping through DOM elements when a certain button is clicked. I've attached the class finish-proc to the button, so when clicked will activate this function:
<script>
$(document).on('click', '.finish-proc', function () {
var communities = [];
var $this, $thisDay, input, inputDay, text, textDay, obj, objDay;
$('.panel-default').each(function (i) {
var maxPeople = '.' + $(this).attr('data-community') + '-max-people';
var dayInfoRow = '.' + $(this).attr('data-community') + '-day-info';
obj = {};
obj["maxPeople"] = $(maxPeople).val();
var daysArrayInLoop = [];
$(dayInfoRow).each(function (j) {
var objDay = {};
var dayString = '.' + $(this).attr('data-community') + '-day-' + (j + 1);
var dayStringStart = '.' + $(this).attr('data-community') + '-day-' + (j + 1) + '-start';
var dayStringEnd = '.' + $(this).attr('data-community') + '-day-' + (j + 1) + '-end';
objDay["dayString"] = $(dayString).val();
objDay["dayStringStart"] = $(dayStringStart).val();
objDay["dayStringEnd"] = $(dayStringEnd).val();
daysArrayInLoop.push(objDay);
}
obj["dayArray"] = daysArrayInLoop;
communities.push(obj);
}
}
</script>
This code is breaking on the line:
daysArrayInLoop.push(objDay);
With the error:
daysArrayInLoop.push is not a function
Can anyone tell me why this is?
EDIT - I've tried to alter the var daysArrayInLoop = []; to var daysArrayInLoop = {};, still getting the same error
Try This code define array after push in object
var daysArrayInLoop = new Array();
daysArrayInLoop.push(obj);
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);
}
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>