Local Storage not fetching more than 6 item - javascript

I am working on a Resume builder website in django. what I wanted is when a user tries to edit prebuild resume template I want to store data in local storage. So that users stay on the page even after refresh. What I have done is created an object which is storing every value of HTML then I have set it to local storage.
but when I getItem then It is fetching only a max 5 elements after that when I change any content in the template it is storing into local storage but not fetching it. Please help me.
<!DOCTYPE html>
<html>
<head>
<title>Resume Template!</title>
<style>
.template
{
background-color:#fafdfc;
height:650px;
width:550px;
border:3px solid blue;
box-shadow:1px 1px 6px;
padding:10px;
float:left;
}
#temp
{
margin:35px 168px;
}
#media print{
body *{
visibility: hidden;
}
.print-container, .print-container *{
visibility: visible;
}
}
</style>
</head>
<body>
<div id="temp" class = "print-container" >
<div class="template" style="float:left; margin-right:15px;">
<div style="float:left;padding:2px;" id="edit0" contenteditable="true" class = "save">
</div>
<div>
<img src="images/resume%20pic.jpg" style="height:100px; width:100px; margin-left:56px; margin-right:20px; margin-top:8px">
</div>
<div style="float:none">
<p style="border-top:1px solid black;"></p>
<p style="font-size:12px; background-color:lightgrey; padding:3px" contenteditable="true">
<b id="edit1" style="padding:3px;" class = "save">CAREER OBJECTIVE</b>
</p>
<p style="font-size:11px;padding:2px;" contenteditable="true" id="edit2" class ="save">To associate myself with a reputed organization where I can utilize my skills to fulfil the goals & objectives of the organization and could enhance my competencies and potential.</p>
<p style="font-size:12px; background-color:lightgrey; padding:3px">
<b contenteditable="true" id="edit3" style="padding:3px;" class = "save">EDUCATIONAL QUALIFICATION</b>
</p>
<table style="font-size:11px; border:1px solid black;padding:4px;" contenteditable="true" id="edit4" class = "save">
<tr>
<td><b id ='course'>Course</b> </td>
<td><b id = 'Board'>Board/University </b></td>
<td><b id = 'Clg-Name'>Name Of Institute </b></td>
<td><b id = 'yearofpassing'>Year Of Passing  </b></td>
<td><b id = 'percentage'>Percentage/CGPA</b></td>
</tr>
<tr>
</tr>
</table>
<p style="font-size:12px; background-color:lightgrey; padding:3px">
<b contenteditable="true" id="edit5" style="padding:3px;" class = "save">TECHNICAL SKILLS</b>
</p>
<ul style="font-size:11px; padding-left:15px;padding-bottom:2px;padding-right:2px;padding-top:2px;" contenteditable="true" id="edit6" class = "save">
<li id = 'tech-skill0'>Beginner of Jquery, Bootstrap, Nodejs, Reactjs, Express, Mongodb.</li>
<li id = 'tech-skill1'>Proficient in C, Python, HTML, CSS.</li>
<li id = 'tech-skill2'>Sufficient Knowledge of C++, SQL, Data Structure, DBMS, Javascript.</li>
</ul>
<p style="font-size:12px; background-color:lightgrey; padding:3px">
<b contenteditable="true" id="edit7" style="padding:3px;" class = "save">TRAININGS ATTENDED</b>
</p>
<ul style="font-size:11px; padding-left:15px;padding-bottom:2px;padding-right:2px;padding-top:2px;" contenteditable="true" id="edit8" class = "save">
<li id = 'training-attended0'>Attended 40 days training on "C++" at "WEBCOM Technologies, Yamunanagar" (June 2019 to July 2019).</li>
<li id = 'training-attended1'>Attended 21.5 hours training on "Python" from "Udemy" (July 2020 to Aug 2020).</li>
</ul>
<p style="font-size:12px; background-color:lightgrey; padding:3px">
<b contenteditable="true" style="padding:3px;" id="edit9" class = "save">ACADEMIC PROJECTS UNDERTAKEN</b>
</p>
<ul style="font-size:11px; padding-left:15px">
<li contenteditable="true" style="padding:2px;" id="edit10" class = "save">
<div style="float:left">
<b id = 'project-name0'>TRAVEL MANIA - </b>
</div>
<div style="font-style:italic; float:right; margin-right:40px" id = 'project-duration0'>(Duration - 2 months)</div>
<div style="float:none">
<br>
<p id = 'project-description0'>(It is a travelling website that enables users to plan their travel without any hassle. It is a team project in which I worked as a front-end developer.)</p>
</div>
<br>
<br>
</li>
</ul>
</div>
</div>
<div class="template">
<ul style="font-size:11px; padding-left:15px">
<li id="edit11" contenteditable="true" style="padding:2px;" class = "save">
<div style="float:left">
<b id = 'project-name1'>JARVIS - PERSONAL ASSISTANT - </b>
</div>
<div style="font-style:italic; float:right; margin-right:48px" id = 'project-duration1'>(Duration - 1 week)</div>
<div style="float:none">
<br>
<p id = 'project-description1'>(This project assists the end-user with day to day activities like searching queries in Google, finding locations, sending emails, playing songs, searching instagram profiles, opening webcam and many more.)</p>
</div>
<br>
</li>
<li id="edit12" contenteditable="true" style="padding:2px;" class = "save">
<div style="float:left">
<b id = 'project-name2'>RESPRO - </b>
</div>
<div style="font-style:italic; float:right; margin-right:40px" id = 'project-duration2'>(Duration - 2 months)</div>
<div style="float:none">
<br>
<p id = 'project-description2'>(It is a website that provides a simple and efficient way of creating resume and cover letter for individuals. It is a team project in which I worked as a front-end developer.)</p>
</div>
</li>
</ul>
<p style="font-size:12px; background-color:lightgrey; padding:3px">
<b id="edit13" contenteditable="true" style="padding:3px;" class = "save">SOFT SKILLS</b>
</p>
<ul style="font-size:11px; padding-left:15px;padding-bottom:2px;padding-right:2px;padding-top:2px;" contenteditable="true" id="edit14" class = "save">
<li id = 'softskill0'>Teamwork</li>
<li id = 'softskill1'>Leadership</li>
<li id = 'softskill2'>Communication skills</li>
<li id = 'softskill3'>Time management</li>
</ul>
<p style="font-size:12px; background-color:lightgrey; padding:3px">
<b contenteditable="true" id="edit15" style="padding:3px;" class = "save">ACHIEVEMENTS</b>
</p>
<ul style="font-size:11px; padding-left:15px;padding-bottom:2px;padding-right:2px;padding-top:2px;" contenteditable="true" id="edit16" class = "save">
<li id = 'Achievement0'>Won third position in FashP competition (2019).</li>
<li id = 'Achievement1'>Won first position in Flower Arrangement competition (2012).</li>
<li id = 'Achievement2'>Won second position in Drawing competition (2012).</li>
<li id = 'Achievement3'>Won certificate for best entry in group D of All India Camel Color Contest (2011).</li>
<li id = 'Achievement4'>Participated in Snacks Making competition (2011).</li>
<li id = 'Achievement5'>Participated in many Dance competitions.</li>
</ul>
<p style="font-size:12px; background-color:lightgrey; padding:3px">
<b contenteditable="true" id="edit17" style="padding:3px;" class = "save">PERSONAL PROFILE</b>
</p>
<p style="font-size:12px;padding:2px;" contenteditable="true" id="edit18" class = "save">
</p>
</div>
</div>
<button id = "safe">Save</button>
<input type="button" id = 'print' onclick = "window.print();" value = "print">
<script src ="script.js" charset="utf-8"></script>
</body>
</html>
Here Is my template I have deleted some private information.
My javaScript File :
window.stop();
document.getElementById("safe").addEventListener("click", function(){
var x = document.querySelectorAll(".save");
for(var i =0; i<x.length; i++)
{
x[i].removeAttribute("contenteditable");
}
});
document.getElementById("temp").addEventListener("click", function(){
var x = document.querySelectorAll(".save");
for(var i = 0; i<x.length; i++){
x[i].setAttribute('contenteditable', "true");
}
});
const element = document.getElementById('temp');
if (typeof Storage !== 'undefined'){
element.addEventListener("keypress", function(event){
const myObject ={
'name': document.getElementById('name').innerText,
'address': document.getElementById('address').innerText,
'mobile': document.getElementById('mobile').innerText,
'e-mail': document.getElementById('e-mail').innerText,
'linkedin': document.getElementById('linkedin-id').innerText,
'career': document.getElementById('edit1').innerText,
'text': document.getElementById('edit2').innerText,
'education': document.getElementById('edit3').innerText,
'course': document.getElementById('course').innerText,
'Board': document.getElementById('Board').innerText,
'Clg-name': document.getElementById('Clg-Name').innerText,
'yearofpassing': document.getElementById('yearofpassing').innerText,
'percentage': document.getElementById('percentage').innerText,
'class0' : document.getElementById('class0').innerText,
'uni-name0': document.getElementById('uni-name0').innerText,
'college0': document.getElementById('college0').innerText,
'year0': document.getElementById('year0').innerText,
'percent0': document.getElementById('percent0').innerText,
'class1': document.getElementById('class1').innerText,
'uni-name1': document.getElementById('uni-name1').innerText,
'college1': document.getElementById('college1').innerText,
'year1': document.getElementById('year1').innerText,
'percent1': document.getElementById('percent1').innerText,
'class2': document.getElementById('class2').innerText,
'uni-name2': document.getElementById('uni-name2').innerText,
'college2': document.getElementById('college2').innerText,
'year2': document.getElementById('year2').innerText,
'percent2': document.getElementById('percent2').innerText,
'edit5': document.getElementById('edit5').innerText,
'tech-skill0': document.getElementById('tech-skill0').innerText,
'tech-skill1': document.getElementById('tech-skill1').innerText,
'tech-skill2': document.getElementById('tech-skill2').innerText,
'edit7': document.getElementById('edit7').innerText,
'training-attended0': document.getElementById('training-attended0').innerText,
'training-attended1': document.getElementById('training-attended1').innerText,
'edit9': document.getElementById('edit9').innerText,
'project-name0': document.getElementById('project-name0').innerText,
'project-duration0': document.getElementById('project-duration0').innerText,
'project-description0': document.getElementById('project-description0').innerText,
'project-name1': document.getElementById('project-name1').innerText,
'project-duration1': document.getElementById('project-duration1').innerText,
'project-description1': document.getElementById('project-description1').innerText,
'project-name2': document.getElementById('project-name2').innerText,
'project-duration2': document.getElementById('project-duration2').innerText,
'project-description2': document.getElementById('project-description2').innerText,
'edit13': document.getElementById('edit13').innerText,
'softskill0': document.getElementById('softskill0').innerText,
'softskill1': document.getElementById('softskill1').innerText,
'softskill2': document.getElementById('softskill2').innerText,
'softskill3': document.getElementById('softskill3').innerText,
'edit15': document.getElementById('edit15').innerText,
'Achievement0': document.getElementById('Achievement0').innerText,
'Achievement1': document.getElementById('Achievement1').innerText,
'Achievement2': document.getElementById('Achievement2').innerText,
'Achievement3': document.getElementById('Achievement3').innerText,
'Achievement4': document.getElementById('Achievement4').innerText,
'Achievement5': document.getElementById('Achievement5').innerText,
'edit17': document.getElementById('edit17').innerText,
'father': document.getElementById('father').innerText,
'father-Name': document.getElementById('father-Name').innerText,
'mother': document.getElementById('mother').innerText,
'mother-Name': document.getElementById('mother-Name').innerText,
'dof': document.getElementById('dof').innerText,
'date': document.getElementById('date').innerText,
'martial-status': document.getElementById('martial-status').innerText,
'status': document.getElementById('status').innerText,
'hobbies': document.getElementById('hobbies').innerText,
'hobby': document.getElementById('hobby').innerText,
};
localStorage.setItem("Content",JSON.stringify(myObject));
})
}
const mysessionData = JSON.parse(localStorage.getItem("Content"));
document.getElementById('edit1').innerText = mysessionData.career
document.getElementById('edit2').innerText = mysessionData.text
document.getElementById('edit3').innerText = mysessionData.education
document.getElementById('course').innerText = mysessionData.course
document.getElementById('Board').innerText = mysessionData.Board
document.getElementById('Clg-name').innerText = mysessionData.Clg-Name
document.getElementById('yearofpassing').innerText = mysessionData.yearofpassing
document.getElementById('percentage').innerText = mysessionData.percentage
document.getElementById('class0').innerText = mysessionData.class0
document.getElementById('uni-name0').innerText = mysessionData.uni-name0
document.getElementById('college0').innerText = mysessionData.college
document.getElementById('year0').innerText = mysessionData.year0
document.getElementById('percent0').innerText = mysessionData.percent0
document.getElementById('class1').innerText = mysessionData.class1
document.getElementById('uni-name1').innerText = mysessionData.uni-name1
document.getElementById('college1').innerText = mysessionData.college1
document.getElementById('year1').innerText = mysessionData.year1
document.getElementById('percent1').innerText = mysessionData.percent1
document.getElementById('class2').innerText = mysessionData.class2
document.getElementById('uni-name2').innerText = mysessionData.uni-name2
document.getElementById('college2').innerText = mysessionData.college2
document.getElementById('year2').innerText = mysessionData.year2
document.getElementById('percent2').innerText = mysessionData.percent2
document.getElementById('edit5').innerText = mysessionData.edit5
document.getElementById('tech-skill0').innerText = mysessionData.tech-skill0
document.getElementById('tech-skill1').innerText = mysessionData.tech-skill1
document.getElementById('tech-skill2').innerText = mysessionData.tech-skill2
document.getElementById('edit7').innerText = mysessionData.edit7
document.getElementById('training-attended0').innerText = mysessionData.training-attended0
document.getElementById('training-attended1').innerText = mysessionData.training-attended1
document.getElementById('edit9').innerText = mysessionData.edit9
document.getElementById('project-name0').innerText = mysessionData.project-name0
document.getElementById('project-duration0').innerText = mysessionData.project-duration0
document.getElementById('project-description0').innerText = mysessionData.project-description0
document.getElementById('project-name1').innerText = mysessionData.project-name1
document.getElementById('project-duration1').innerText = mysessionData.project-duration1
document.getElementById('project-description1').innerText = mysessionData.project-description1
document.getElementById('project-name2').innerText = mysessionData.project-name2
document.getElementById('project-duration2').innerText = mysessionData.project-duration2
document.getElementById('project-description2').innerText = mysessionData.project-description2
document.getElementById('edit13').innerText = mysessionData.edit13
document.getElementById('softskill0').innerText = mysessionData.softskill0
document.getElementById('softskill1').innerText = mysessionData.softskill1
document.getElementById('softskill2').innerText = mysessionData.softskill2
document.getElementById('softskill3').innerText = mysessionData.softskill3
document.getElementById('edit15').innerText = mysessionData.edit15
document.getElementById('Achievement0').innerText = mysessionData.Achievement0
document.getElementById('Achievement1').innerText = mysessionData.Achievement1
document.getElementById('Achievement2').innerText = mysessionData.Achievement2
document.getElementById('Achievement3').innerText = mysessionData.Achievement3
document.getElementById('Achievement4').innerText = mysessionData.Achievement4
document.getElementById('Achievement5').innerText = mysessionData.Achievement5
document.getElementById('edit17').innerText = mysessionData.edit17
document.getElementById('father').innerText = mysessionData.father
document.getElementById('father-name').innerText = mysessionData.father-Name
document.getElementById('mother').innerText = mysessionData.mother
document.getElementById('mother-name').innerText = mysessionData.mother-Name
document.getElementById('dof').innerText = mysessionData.dof
document.getElementById('date').innerText = mysessionData.date
document.getElementById('martial-status').innerText = mysessionData.martial-status
document.getElementById('status').innerText = mysessionData.status
document.getElementById('hobbies').innerText = mysessionData.hobbies
document.getElementById('hobby').innerText = mysessionData.hobby
I know I have written very weird javascript but please Help me.
Or suggest some other way to do the same thing. I don’t know much I am just a beginner in web development.

You can not read properties containing hyphens in the property name like this :
'-', '+', '*' etc. are operands. You can understand why they will not work.
document.getElementById('Clg-name').innerText = mysessionData.Clg-Name
Try this :
document.getElementById('Clg-name').innerText = mysessionData['Clg-Name'];

Related

Display items on web page using AJAX and DOM

For this challenge, I am using AJAX to load contents to my web page, the first problem I have is to display the projects on the page. I have DOM selected the and I am trying to append as required but they still won't display. What am I missing? Secondly, my edit button is not behaving as I want it to.
const today = new Date();
const thisYear = today.getFullYear()
const footer = document.querySelector('footer');
const copyright = document.createElement('p');
copyright.innerHTML = `<span> © Erick Odero ${thisYear}</span> `;
footer.appendChild(copyright);
let skills = ['html', 'CSS', 'JavaScript'];
const skillsSection = document.getElementById('skills');
const skillsList = document.getElementById('skills').children[1];
for (let i = 0; i < skills.length; i++) {
const skill = document.createElement('li');
skill.textContent = skills[i];
skillsList.appendChild(skill);
}
// Create and handle edit button
const editMessage = document.querySelector('#text_message');
const editButton = document.createElement('button');
editButton.innerText = 'Edit';
editButton.type = 'button';
editButton.classList.add('btn');
editMessage.appendChild(editButton);
editMessage.addEventListener('click', (e) => {
const button = e.target;
const span = document.createElement('span');
const editedMessage = document.createElement('input');
input.type = 'text';
console.log(newMessage);
})
// Handle message form submit button
const messageForm = document.querySelector('form[name="leave_message"]')
messageForm.addEventListener('submit', (e) => {
// prevent default refreshing behavior
e.preventDefault();
// create variables for each form field
// const user_name = messageForm.name.value;
// const user_email = messageForm.email.value;
// const user_message = messageForm.message.value;
const user_name = e.target.name;
const user_email = e.target.email;
const user_message = e.target.message;
// Display messages in list
const messageSection = document.getElementById('messages');
const messageList = messageSection.children[1];
const newMessage = document.createElement('li');
newMessage.innerHTML = `${user_name.value}<span> wrote: ${user_message.value}</span>`;
// create button element
const removeButton = document.createElement('button');
removeButton.innerText = 'remove';
removeButton.type = 'button';
// handle the removeButton
removeButton.addEventListener('click', (e) => {
const entry = e.target.parentNode;
entry.remove();
})
// reset the form
messageForm.reset();
newMessage.appendChild(removeButton);
messageList.appendChild(newMessage);
})
const header = document.getElementById('header');
header.classList.add('sticky');
var gitHubRequest = new XMLHttpRequest();
gitHubRequest.onreadystatechange = function() {
if (gitHubRequest.readyState === 4 && gitHubRequest.status === 200) {
gitHubRequest.responseText;
}
};
gitHubRequest.open('GET', 'https://api.github.com/users/eodero/repos');
gitHubRequest.send();
gitHubRequest.addEventListener('load', (event) => {
let repositories = JSON.parse(gitHubRequest.response);
console.log(repositories);
});
const projectSection = document.getElementById('projects');
const projectList = projectSection.lastElementChild;
for (let i = 0; i < projectList.length; i++) {
const project = document.createElement('li');
project.innerText += project[i];
projectList.appendChild(project);
console.log(projectSection);
}
<!DOCTYPE html>
<html>
<head>
<title>erick_odero-portfolio</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edgev">
<link rel="stylesheet" href="index.css">
<script src="https://kit.fontawesome.com/631b2dc748.js" crossorigin="anonymous"></script>
</head>
<body>
<section class="list">
<header id="header">
<h1 id="my-name">Erick O Odero</h1>
<img src="https://avatars.githubusercontent.com/u/84427589?v=4" alt="Author's profile picture" width="60" height="60">
<nav class="main-menu">
<ul>
<li>Home</li>
<li>About</li>
<li>Projects</li>
<li>Connect</li>
</ul>
</nav>
</header>
</section>
<main>
<section id="about">
<h1>About</h1>
<p> I am healthcare worker in the field of clinical research residing in Memphis Tennessee and now an aspiring
<br> Software Developer. I am currently a student with Code The Dream taking Javascript, HTML, AJAX and <br> Fetch API lessons. When I learnt of the immense potential that technology has to improve health outcomes<br> of our communities, my interest
in coding was conjured and I hope to immerse myself full time in the industry.
</p>
</section>
<section class="list">
<h1>Experience</h1>
<ul id="exp">
<li>clinical Research Associate - United States</li>
<li>HIV program coordinator - Kenya</li>
<li>Health program coordinator - Kenya</li>
<li>Health Worker Training and Capacity building(volunteer) - Vanuatu</li>
</ul>
</section>
<section class="list">
<h1>My tools</h1>
<ul class="tools">
<li>Visual Studio Code</li>
<li><a href="https://www.apple.com/macbook-air/?afid=p238%7CsS5GAoNB9-dc_mtid_1870765e38482_pcrid_569734191494_pgrid_110391415659_&cid=aos-us-kwgo-mac--slid---product-">Mac
Bookair</a></li>
<li>Windows 10</li>
<li>Slack</li>
<li>Freecodecamp</li>
<li>Whimsical
</li>
<li>github</li>
</ul>
</section>
<section class="section">
<h1>My resume</h1>
<nav>
<ul>
<li>resume</li>
</ul>
</nav>
</section>
<section id="skills">
<h2 class="list">Skills</h2>
<ul id="skillz"></ul>
</section>
<section id="projects">
<h2>Projects</h2>
<ul>
</ul>
</section>
</main>
<!--Create leave message section and add form-->
<section class="section">
<h2>Leave a Message</h2>
<form name="leave_message">
<fieldset id="details">
<legend>1 Your details</legend>
<label for="name">Name:</label><br>
<input type="text" name="name" required="true"><br>
<label for="email">Email:</label><br>
<input type="email" name="email" required="true"><br>
</fieldset>
<fieldset id="text_message">
<legend>2 Your Message</legend>
<label for="message">Message:</label><br>
<textarea id="textMessage" name="message" required="true"></textarea><br>
</fieldset>
<button id="submit" class="btn" type="submit">Submit</button>
</form>
</section>
<!-- Add message list section-->
<section id="messages">
<h2>Messages</h2>
<ul>
</ul>
</section>
<footer></footer>
<script src="index.js"></script>
</body>
</html>

Issues with code for a simple on page search

I am trying to build a simple on page search that uses event listeners to look at a containers data and then hides that whole container if it doesn't have the required information.
So far I have:
// get search element
let searchInput = document.getElementById ('searchInput');
// add event listener
searchInput.addEventListener ('keyup', searchPage);
function searchPage(){
//search input detection
let searchValue = document.getElementById('searchInput').value;
//set parameters to search from
let parent = document.getElementById('product-container');
let child = parent.getElementsByTagName('span');
for(let i = 0;i < child.length;i++){
let a = child[i];
if(a.innerHTML.indexOf(searchValue) >= -1) {
child[i].parentNode.style.display = '';
} else {
child[i].parentNode.style.display = 'none';
};
};
};
But this only acts on the first product-container it finds, there are 5 such containers on the page.
How do I make this look through all containers, but hide the ones that don't contain any of the information typed in the search bar.
I am getting products from an API so using html replace to add to the following template:
<script id="template" type="text/template">
<div class="product">
<div class="product--header">{{ type }}</div>
<div class="product--image"><img src="../app/assets/images/no-image.png" alt="no image"> </div>
<div class="product--information" id="product--information">
<div class="product--title"><span>{{ name }}</span></div>
<!--This is just a place holder we would house the prices here if they were on the API -->
<div class="product--price">£55</div>
<div class="product--brand"><strong>Brand:</strong><span> {{ brand }}</span></div>
<div class="product--colour"><strong>Colour:</strong><span> {{ colour }}</span></div>
<div class="product--sizes">
<select>
<option value="" disabled selected>Select Size </option>
{{ options }}
</select>
</div>
<div class="product--description"><strong>Description:</strong><br><div class="product--description__content"><span> {{ description }} </span></div></div>
<div class="product--code"><strong>Product ID:</strong><span> {{ productid }}</span></div>
<div class="product--buttons">
<button class="btn--buy" aria-label="Add to Basket">Add to basket</button>
<button class="btn--save" aria-label="Save for Later">Save for later</button>
</div>
<button class="product--add-to-wishlist" aria-label="Add to Wishlist"><i class="fas fa-heart"></i></button>
</div>
</div>
</script>
The search box code is as follows:
<input type="text" name="search" id="searchInput" placeholder="Enter Search...">
and the code that the template goes into is:
<div id="product-container">
<div class="featured"></div>
<div class="products"></div>
</div>
Because you have multiple product containers, use document.getElementsByClassName() instead of document.getElementById() and provide product-container class as argument.
let searchInput = document.getElementsByClassName ('container');
You need to modify searchPage() method. Instead of using document to find searchValue and parent use this.
let searchValue = this.getElementsByClassName('searchInput')[0].value;
let parent = this.getElementsByClassName('container')[0];
Please, add HTML code.
EDIT: If I understand correctly you have one search input which will search multiple product containers. Here is one simple example, which you can easily apply to your problem.
HTML:
<input type="text" name="search" id="searchInput" placeholder="Enter Search...">
<div class="product-container">
<span class="product">Kiwi</span>
<p>Kiwi description</p>
</div>
<div class="product-container">
<span class="product">Banana</span>
<p>Banana description</p>
</div>
<div class="product-container">
<span class="product">Apple</span>
<p>Apple description</p>
</div>
JS:
let searchInput = document.getElementById ('searchInput');
searchInput.addEventListener ('keyup', searchPage);
function searchPage(){
let searchValue = this.value.toUpperCase();
let products = document.getElementsByClassName('product');
for(let i = 0; i < products.length; i++) {
console.log(products[i].innerHTML.toUpperCase());
if (products[i].innerHTML.toUpperCase().indexOf(searchValue) > -1)
products[i].parentNode.style.display = '';
else
products[i].parentNode.style.display = 'none';
};
};
CSS:
.product-container {
display: flex;
flex-direction: column;
margin-bottom: 10px;
background: grey;
}
.product-container span {
font-size: 20px;
}
.product {
display: block;
}
https://jsfiddle.net/gardelin/koc5eg6v/25/

Need to card images on cards for a memory game in JavaScript

I am working on a memory game, still. I have 36 images and an array of 36 numbers. I am randomly having numbers picked from the array that make up the 18 numbers for the cards. I need to create the cards and I am trying to append li's to a ul I have in the HTML.
Here is my HTML:
<!DOCTYPE html>
<!-- Group 5 CSD 122 The Holodeck - Games-->
<html>
<head>
<title>Games</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script defer src="https://use.fontawesome.com/releases/v5.0.13/js/all.js" integrity="sha384-xymdQtn1n3lH2wcu0qhcdaOpQwyoarkgLVxC/wZ5q7h9gHtxICrpcaSUfygqZGOe" crossorigin="anonymous"></script>
<link rel = "stylesheet" type = "text/css" href = "LCARSremake.css">
<link rel = "stylesheet" type = "text/css" href = "matchingGame.css">
<script src = "javascript/matchingGame.js"></script>
</head>
<body>
<div class = "recFrame">
<header>
<div id = "header" class = "lcars-row header">
<div class="lcars-elbow left-bottom"></div>
<div class="lcars-bar horizontal">
<div><h1 class = "title right"> Matching Game </h1></div>
</div>
<div class="lcars-bar horizontal right-end decorated"></div>
</div>
</header>
<div id = "leftmenu" class = "lcars-column start-space lcars-u-1">
<ul style = "list-style-type: none" class = "leftmenu">
<li class = "lcars-u-1 blank1"></li>
<li class = "lcars-u-1 home"> Home </li>
<li class = "lcars-u-1 games"> Games </li>
<li class = "lcars-u-1 about"> About </li>
<li class = "lcars-u-1 blank2"></li>
<li class = "lcars-u-1 blank3"></li>
<li class = "lcars-u-1 blank4"></li>
<li class = "lcars-u-1 blank5"></li>
<li class = "lcars-u-1 blank6"></li>
<li class = "lcars-u-1 blank7"></li>
</ul>
<div class="lcars-bar lcars-u-1"></div>
</div>
<main>
<div id = "contentFrame">
<div class = "lcars-column lcars-u-5">
<section class = "score-panel">
<div id = "startGame">Start Game</div>
<ul class = "rank">
<li><i class="fas fa-circle"></i></li>
<li><i class="fas fa-circle"></i></li>
<li><i class="fas fa-circle"></i></li>
<li><i class="fas fa-circle"></i></li>
</ul>
<span class = "moves">0 </span> MOVES | TIME:
<div class = "timer"></div>
<div class = "restart">
<i class="fas fa-redo"></i>
</div>
</section>
<ul class = "deck">
</ul>
<div id="popup1" class="overlay">
<div class="popup">
<h2>Congratulations</h2>
<a class="close" href=# >×</a>
<div class="content-1">
Congratulations you won!
</div>
<div class="content-2">
<p>You made <span id=finalMove> </span> moves </p>
<p>in <span id=totalTime> </span> </p>
<p>Rating: <span id=starRating></span></p>
</div>
<button id="play-again"onclick="playAgain()">
Play again</a>
</button>
</div>
</div>
</div>
</div>
</main>
<footer>
<div id = "footer" class = "lcars-row">
<div class="lcars-elbow left-top"></div>
<div class="lcars-bar horizontal both-divider bottom"></div>
<span class = "footerContent"><p> LCARS © Michael Okuda </p></span>
<div class="lcars-bar horizontal right-end left-divider bottom"></div>
</div>
</footer>
</div>
</body>
</html>
Here is the javascript code I'm trying to use to get the images to be the list item:
// The function init() enables the game to begin
function init() {
// The shuffle function shuffles the objects array
let allCards = shuffle(cardList());
$deck.empty();
// The game starts with no matching cards and zero moves
match = 0;
moves = 0;
$moves.text('0');
// A for loop creates <li> tags with the class of card for every <i> tag
// A class of fa fa- and a name of each object from the objects=[] array
for (let i = 0; i < allCards.length; i++) {
var img = allCards[i] + '.png';
$deck.append(('<li class="card"><img src = "images/symbols/ ' + img + '/>/li>'))
}
addCardListener();
// Enables the timer to reset to 0 when the game is restarted
resetTimer(nowTime);
second = 0;
$timer.text(`${second}`)
initTime();
}
Using the debugger and I get to the part where it is supposed to append, I just get the content from here displayed:
https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js
I have no idea what $deck is since you did not provide that so I have to somewhat guess. Just a side note you apparently have a number of global variables, never a good idea.
This line is not producing valid HTML:
$deck.append(('<li class="card"><img src = "images/symbols/ ' + img + '/>/li>'))
Compare to
$deck.append('<li class="card"><img src = "images/symbols/' + img + '"/></li>');
Note it would be much better to create all the elements, then append them one time to the DOM instead of hitting it multiple times.
SO, assuming markup as such:
<ul id="deck"></ul>
Script such as:
var $deck = $('#deck');
var mycards = $('<div/>');
var li = $('<li class="card"><img /></li>');
for (let i = 0; i < allCards.length; i++) {
var imgsrc = 'images/symbols/'+ allCards[i] + '.png';
li.find('img').prop('src',imgsrc);
mycards.append(li);
}
$deck.append(mycards.find('li'));
$deck.append(('<li class="card"><img src = "images/symbols/ ' + img + '/>/li>'))
should be
$deck.append('<li class="card"><img src="images/symbols/' + img + '" /></li>'))

Var wont display [duplicate]

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 3 years ago.
So I'm bored so I decided to learn javascript an I came across this weird bug where one of my variables wont display even though it is the same code for both of them.
var wheatFields = 0;
var numWheat = 0;
var wheat = 0;
window.onload = function() {
document.getElementById("wheatFarms").innerHTML = wheatFields;
document.getElementById("numWheat").innerHTML = numWheat;
document.getElementById("wheatNum").innerHTML = wheat;
};
function addWheatFarm() {
wheatFields++;
document.getElementById("wheatFarms").innerHTML = wheatFields;
//wheatHandler();
}
function wheatHandler() {
var lifespan = Math.floor(Math.Random() * 50) + 10;
for (var i = 0; i <= lifespan; i++) {
wheat++;
document.getElementById("wheatNum").innerHTML = wheat;
}
}
<div data-role="page" id="start">
<div class="header">
<h1>Farming Game</h1>
</div>
<div data-role="main" class="ui-content">
<button id="wheatButton" onclick="addWheatFarm()">
Add a wheat farm.
</button>
</br>
<br>
<div id="fieldContainer" class="containers">
<ul data-role="listview" id="farms" data-count-theme="b" data-insert="true">
<br>
<li id="fieldCounter">
<p>Wheat Fields
<var id="wheatFarms"></var>
</p>
</li>
</ul>
</br>
</br>
</div>
<div id="inventoryContainer" class="containers">
<ul data-role="listview" id="inventory" data-count-theme="b" data-insert="true">
<li id="wheatCounter">
<p>Wheat <span id="wheatNum"></span>
<!--<p id = "wheatNum"></p>-->
</p>
</li>
</ul>
</div>
</div>
</div>
I'm not quite sure where I am going wrong. I did the same thing for both of them and I don't know why it works for one and not the other. The number of wheat farms displays and will update when I click the button. but the number of wheat wont even show the 0 starting value.
You should check out the console, when it says on this line:
document.getElementById("numWheat").innerHTML = numWheat;
Throws this error because there's no element there with id="numWheat":
Uncaught TypeError: Cannot set property 'innerHTML' of null
So all the code after that got stopped working. Remove that line and everything works.
Also, Math.Random() is not right. It's Math.random().
Fully Corrected Code
var wheatFields = 0;
var numWheat = 0;
var wheat = 0;
window.onload = function(){
document.getElementById("wheatFarms").innerHTML = wheatFields;
document.getElementById("wheatNum").innerHTML = wheat;
};
function addWheatFarm() {
wheatFields++;
document.getElementById("wheatFarms").innerHTML = wheatFields;
wheatHandler();
}
function wheatHandler(){
var lifespan = Math.floor(Math.random() * 50) + 10;
for (var i = 0; i <= lifespan; i++) {
wheat++;
document.getElementById("wheatNum").innerHTML = wheat;
}
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="stylesheet.css">
<script type="text/javascript" src="Scripts.js"></script>
</head>
<body>
<div data-role = "page" id = "start">
<div class = "header">
<h1>Farming Game</h1>
</div>
<div data-role = "main" class = "ui-content">
<button id = "wheatButton" onclick = "addWheatFarm()">
Add a wheat farm.
</button>
</br>
<br>
<div id = "fieldContainer" class = "containers">
<ul data-role = "listview" id = "farms" data-count-theme = "b" data-insert = "true">
<br>
<li id = "fieldCounter">
<p>Wheat Fields
<var id = "wheatFarms"></var>
</p>
</li>
</ul>
</br>
</br>
</div>
<div id = "inventoryContainer" class = "containers">
<ul data-role = "listview" id = "inventory" data-count-theme = "b" data-insert = "true">
<li id = "wheatCounter">
<p>Wheat <span id = "wheatNum"></span>
<!-- <p id = "wheatNum"></p> -->
</p>
</li>
</ul>
</div>
</body>
</html>
Try this it will work
https://jsfiddle.net/debashishkumar/4mf1mvkc/
<div data-role="page" id="start">
<div class="header">
<h1>Farming Game</h1>
</div>
<div data-role="main" class="ui-content">
<button id="wheatButton" onclick="addWheatFarm(12)">
Add a wheat farm.
</button>
<br>
<div id="fieldContainer" class="containers">
<ul data-role="listview" id="farms" data-count-theme="b" data-insert="true">
<br>
<li id="fieldCounter">
<p>Wheat Fields
<var id="wheatFarms"></var>
</p>
</li>
</ul>
<div id="inventoryContainer" class="containers">
<ul data-role="listview" id="inventory" data-count-theme="b" data-insert="true">
<li id="wheatCounter">
<p>Wheat <span id="wheatNum"></span>
<p id = "wheatNum"></p>
</p>
</li>
</ul>
</div>
</div>
</div>
<script>
var wheatFields = 0;
var numWheat = 0;
var wheat = 0;
window.onload = function() {
document.getElementById("wheatFarms").innerHTML = wheatFields;
document.getElementById("numWheat").innerHTML = numWheat;
document.getElementById("wheatNum").innerHTML = wheat;
};
function addWheatFarm() {
wheatFields++;
document.getElementById("wheatFarms").innerHTML = wheatFields;
wheatHandler();
}
function wheatHandler() {
var lifespan = Math.floor(Math.random() * 50) + 10;
for (var i = 0; i <= lifespan; i++) {
wheat++;
document.getElementById("wheatNum").innerHTML = wheat;
}
}
</script>

how to create generic html with javascript

I have the following html:
<div id="prog" class="downloads clearfix">
<div class="item">
<div class="image_container">
<img src="/img/downloads/company.png" width="168" height="238" alt="">
</div>
<div class="title">
pricelist: <label id="pr1"></label>
</div>
<div class="type">
pdf document
</div>
<div class="link">
<a id="pdfdocument" class="button" target="_blank" href="#">start Download </a>
</div>
</div>
</div>
I want build HTML which is inside the <div id="prog"> with Javascript:
<div id="prog" class="downloads clearfix"></div>
I'm trying to use this Javascript, but without success:
var tmpDocument, tmpAnchorTagPdf, tmpAnchorTagXls, parentContainer, i;
parentContainer = document.getElementById('prog');
for (i = 0; i < documents.length; i++) {
tmpDocument = documents[i];
tmpAnchorTagPdf = document.createElement('a id="pdfdocument" ');
tmpAnchorTagPdf.href = '/role?element=' + contentElement.id + '&handle=' + ope.handle;
tmpAnchorTagPdf.innerHTML = 'start Download';
tmpAnchorTagXls = document.createElement('a');
tmpAnchorTagXls.href = '/role?element=' + contentElement.id + '&handle=' + ope.handle;
tmpAnchorTagXls.innerHTML = 'start Download';
parentContainer.appendChild(tmpAnchorTagPdf);
parentContainer.appendChild(tmpAnchorTagXls);
}
If this is a section of code that you will be using more than once, you could take the following approach.
Here is the original div without the code you want to create:
<div id="prog" class="downloads clearfix">
</div>
Create a template in a hidden div like:
<div id="itemtemplate" style="display: none;">
<div class="item">
<div class="image_container">
<img src="/img/downloads/company.png" width="168" height="238" alt="">
</div>
<div class="title">
pricelist: <label></label>
</div>
<div class="type">
pdf document
</div>
<div class="link">
<a class="button" target="_blank" href="#">start Download </a>
</div>
</div>
</div>
Then duplicate it with jquery (OP originally had a jquery tag; see below for JS), update some HTML in the duplicated div, then add it to the document
function addItem() {
var item = $("#itemtemplate div.item").clone();
//then you can search inside the item
//let's set the id of the "a" back to what it was in your example
item.find("div.link a").attr("id", "pdfdocument");
//...the id of the label
item.find("div.title label").attr("id", "pr1");
//then add the objects to the #prog div
$("#prog").append(item);
}
update
Here is the same addItem() function for this example using pure Javascript:
function JSaddItem() {
//get the template
var template = document.getElementById("itemtemplate");
//get the starting item
var tempitem = template.firstChild;
while(tempitem != null && tempitem.nodeName != "DIV") {
tempitem = tempitem.nextSibling;
}
if (tempitem == null) return;
//clone the item
var item = tempitem.cloneNode(true);
//update the id of the link
var a = item.querySelector(".link > a");
a.id = "pdfdocument";
//update the id of the label
var l = item.querySelector(".title > label");
l.id = "pr1";
//get the prog div
var prog = document.getElementById("prog");
//append the new div
prog.appendChild(item);
}
I put together a JSFiddle with both approaches here.

Categories