How can I remove this error from my console? - javascript

I receive the following error:
Uncaught ReferenceError: notesObj is not defined
at HTMLButtonElement.<anonymous> (apps.js:14)
I could store the object earlier in the local storage and there was no error generated. But after the removal of the 'card' division after 'your notes' it is now difficult for me to remove the error.
//shownotes();
//If user add a note, add it to the local storage
let addBtn = document.getElementById('addBtn')
addBtn.addEventListener('click', function(e) {
let addTxt = document.getElementById('addTxt');
let notes = localStorage.getItem('notes');
if (notes == null) {
notesObj = [];
} else {
nodesObj = JSON.parse(notes);
}
notesObj.push(addTxt.value)
localStorage.setItem('notes', JSON.stringify(notesObj));
addTxt.value = '';
console.log(notesObj);
shownotes();
})
function shownotes() {
let notes = localStorage.getItem('notes');
if (notes == null) {
notesObj = [];
} else {
nodesObj = JSON.parse(notes);
}
let html = '';
notesObj.forEach(function(element, index) {
html += `<div class="card my-3 mx-3" style="width: 18rem;">
<div class="card-body">
<h5 class="card-title">Notes ${index + 1}</h5>
<p class='card-text'>${element}</p>
Add Notes
<buttom href="#" class="btn btn-danger my-3">Delete notes</button>
</div>
</div>`
});
let notesElm = document.getElementById('notes')
if (notes.length != 0) {
notesElm.innerHTML = html;
} else {
notesElm.innerHTML = `Nothing to show! Use 'Add notes section above to add notes `
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Make notes!</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container-fluid">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#">Home</a>
</li>
</ul>
<form class="d-flex">
<input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success" type="submit">Search</button>
</form>
</div>
</div>
</nav>
<div class="container my-3 text-center">
<h1>Magic notes</h1>
<div class="card">
<div class="card-body">
<h5 class="card-title">Quick notes</h5>
<div class="form-floating">
<textarea class="form-control" id="addTxt" rows="3" style="height: 100px"></textarea>
<!-- <label for="floatingTextarea2">Add your notes here</label> -->
</div>
<button href="#" class="btn btn-primary my-3" id="addBtn">Add notes</button>
</div>
</div>
</div>
<hr>
<h1 class="text-center">Your notes</h1>
<hr>
<div id="notes" class="row container-fluid">
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous"></script>
</body>
</html>

Well, from the code you provided, it appears to me that you try to use nodesObj before it was ever defined anywhere. I think you meant notesObj. Either define nodesObj like this, or fix the typo.
You may want to do something like
Now my java script code is from here.
var nodesObj = new Array(); // Declare the variable BEFORE using it anywhere.
console.log('This is the notes app.')
//shownotes();
//If user add a note, add it to the local storage
let addBtn = document.getElementById('addBtn')
addBtn.addEventListener('click', function (e) {
let addTxt = document.getElementById('addTxt');
let notes = localStorage.getItem('notes');
if (notes == null) {
notesObj = [];
}
else {
nodesObj = JSON.parse(notes);
}
notesObj.push(addTxt.value)
localStorage.setItem('notes', JSON.stringify(notesObj));
addTxt.value = '';
console.log(notesObj);
shownotes();
})
function shownotes() {
let notes = localStorage.getItem('notes');
if (notes == null) {
notesObj = [];
}
else {
nodesObj = JSON.parse(notes);
}
let html = '';
notesObj.forEach(function (element, index) {
html += `<div class="card my-3 mx-3" style="width: 18rem;">
<div class="card-body">
<h5 class="card-title">Notes ${index + 1}</h5>
<p class='card-text'>${element}</p>
Add Notes
<buttom href="#" class="btn btn-danger my-3">Delete notes</button>
</div>
</div>`
});
let notesElm = document.getElementById('notes')
if (notes.length != 0) {
notesElm.innerHTML = html;
}
else {
notesElm.innerHTML = `Nothing to show! Use 'Add notes section above to add notes `
}
}

you write somethings wrong
test it
console.log('This is the notes app.')
//shownotes();
//If user add a note, add it to the local storage
let addBtn = document.getElementById('addBtn')
var nodesObj = new Array();
var notesObj = new Array();
addBtn.addEventListener('click', function (e) {
let addTxt = document.getElementById('addTxt');
let notes = localStorage.getItem('notes');
if (notes == null) {
notesObj = [];
}
else {
nodesObj = JSON.parse(notes);
}
notesObj.push(addTxt.value)
localStorage.setItem('notes', JSON.stringify(notesObj));
addTxt.value = '';
console.log(notesObj);
shownotes();
})
function shownotes() {
let notes = localStorage.getItem('notes');
if (notes == null) {
notesObj = [];
}
else {
nodesObj = JSON.parse(notes);
}
let html = '';
notesObj.forEach(function (element, index) {
html += `<div class="card my-3 mx-3" style="width: 18rem;">
<div class="card-body">
<h5 class="card-title">Notes ${index + 1}</h5>
<p class='card-text'>${element}</p>
Add Notes
<buttom href="#" class="btn btn-danger my-3">Delete notes</button>
</div>
</div>`
});
let notesElm = document.getElementById('notes')
if (notes.length != 0) {
notesElm.innerHTML = html;
}
else {
notesElm.innerHTML = `Nothing to show! Use 'Add notes section above to add notes `
}
}

Related

javascript in django template not working

I'm new in Django, im create product page in Django in product card i add increment decrement add to cart button, but add to cart button work on first product card so,what can i do?
I'm added add to card increment and decrement button using JavaScript why JavaScript only apply on one card product in Django. so, how to resolve when ever i use looping in Django my JavaScript not working or shown in console btn varriable already declared.
{% for i in productskey %}
<div class="col-sm-4">
<div class="product-image-wrapper" style="border:1px solid #ddd ;">
<div class="single-products">
<div class="productinfo text-center">
<a href="{% url 'prodetail' i.id %}">
<img src=" {{i.productImage.url}} " alt="" style="width:255px; height:255px"/>
</a>
<h2>₹{{i.productPrice}}</h2>
<p>{{i.productName}}</p>
<div class="btn">
<button class="mainusbtn">-</button>
<button class="mainbtn" class="btn btn-default" class="fa fa-shopping-cart">ADD TO CART</button>
<button class="plusbtn">+</button>
</div>
<!-- <i class="fa fa-shopping-cart"></i>Add to cart -->
</div>
<!-- <div class="product-overlay">
<div class="overlay-content">
<h2>$56</h2>
<p>Easy Polo Black Edition</p>
<i class="fa fa-shopping-cart"></i>Add to cart
</div>
</div> -->
</div>
<!-- <div class="choose">
<ul class="nav nav-pills nav-justified">
<li><i class="fa fa-plus-square"></i>Add to wishlist</li>
<li><i class="fa fa-plus-square"></i>Add to compare</li>
</ul>
</div> -->
</div>
<!-- </a> -->
</div>
<script>
let btn = document.querySelector('.mainbtn');
let pbtn = document.querySelector('.plusbtn');
let mbtn = document.querySelector('.mainusbtn');
btn.addEventListener("click", () => {
if (btn.innerText == 'ADD TO CART') {
btn.innerText = 1;
pbtn.style.display = 'inline-block';
mbtn.style.display = 'inline-block';
}
})
mbtn.addEventListener("click", () => {
if (btn.innerText == 5) {
pbtn.style.display = 'inline-block';
}
if (btn.innerText < 2) {
btn.innerText = 'ADD TO CART';
pbtn.style.display = 'none';
mbtn.style.display = 'none';
} else {
btn.innerText = btn.innerText - 1;
}
})
pbtn.addEventListener("click", () => {
btn.innerText = +(btn.innerText) + +1;
// if(btn.innerText == 5){
// pbtn.style.display = 'none';
// }
})
</script>

Can someone explain why my modal isn't working. I think it has to do with my populateEpisodes function because the getEpisodes array is returned fine

Top section is my HTML, bottom is my Javascript. This is my first time using stackoverflow, so I may have formatted the code wrong on here. My modal won't connect to the 'get episodes' button for some reason. I think it has something to do with my populateEpisodes function because getEpisodes console.logs the array of episodes object, so I have the array but I can't figure out why my modal won't work.
const missingPhotoURL = "URL stack wouldn't let me post";
async function searchShows(query) {
let showRequest = await axios.get(`http://api.tvmaze.com/search/shows?q=${query}`);
let showArray = [];
for(let show of showRequest.data){
let showObj = {
id: show.show.id,
name: show.show.name,
summary: show.show.summary,
image: show.show.image ? show.show.image.medium : missingPhotoURL
};
showArray.push(showObj)
}
console.log(showRequest);
console.log(showArray);
return showArray; //returns array of show objects
}
function populateShows(shows) {
const $showsList = $("#shows-list");
$showsList.empty();
for (let show of shows) {
let $show = $(
`<div class="col-md-6 col-lg-3 Show" data-show-id="${show.id}">
<div class="card" data-show-id="${show.id}">
<div class="card-body" id = "showCard">
<img class="card-img-top" src=${show.image}>
<h5 class="card-title">${show.name}</h5>
<p class="card-text">${show.summary}</p>
<button class="btn btn-outline-primary get-episodes" id="episodeButton" data-bs-toggle="modal" data-bs-target="#episodeModal">Show Episodes</button>
</div>
</div>
</div>
`
);
$showsList.append($show);
}
}
$("#search-form").on("submit", async function handleSearch (evt) {
evt.preventDefault();
let query = $("#search-query").val();
if (!query) return;
$("#episodes-area").hide();
let shows = await searchShows(query);
populateShows(shows);
});
async function getEpisodes(id) {
let episodesRequest = await axios.get(
`http://api.tvmaze.com/shows/${id}/episodes`
);
console.log(episodesRequest);
let episodeArray = [];
for(let episode of episodesRequest.data){
let episodeObj = {
id: episode.id,
name: episode.name,
season: episode.season,
number: episode.number,
};
episodeArray.push(episodeObj);
}
console.log(episodeArray);
return episodeArray;
}
async function populateEpisodes(episodes){
const $episodesModalBody = $('.modalBody')
//$episodesModalBody.empty();
for(let episode of episodes){
let $episodeBody = $(
`<p> ${episode.name} (Season:${episode.season} Episode:${episode.number})</p>`
);
$episodesModalBody.append($episodeBody);
}
}
$('#shows-list').on('click', '.get-episodes', async function episodeClick(e){
let showID = $(e.target).closest('.Show').data('show-id');
let episodes = await getEpisodes(showID);
populateEpisodes(episodes);
})
<!doctype html>
<html>
<head>
<title>TV Maze</title>
<link rel="stylesheet" href="https://unpkg.com/bootstrap/dist/css/bootstrap.css">
</head>
<body>
<h1>TV Maze</h1>
<form class="form-inline" id="search-form">
<input class="form-control" id="search-query" placeholder = 'Show Name'>
<button class="btn btn-primary" type="submit">Go!</button>
</form>
<div class="row mt-3" id="shows-list">
<div class = 'modal fade' id = 'episodeModal' tabindex = '-1'>
<div class = 'modal-dialog modal-dialog-scrollable' >
<div class = 'modal-content'>
<div class = 'modal-header'>
<h5>Episode List:</h5>
</div>
<div class = 'modal-body'>
</div>
<div class = 'modal-footer'>
<button type="button" class="btn btn-outline-danger" data-bs-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
<script src="http://unpkg.com/jquery"></script>
<script src="http://unpkg.com/axios/dist/axios.js"></script>
<script src="tvmaze.js"></script>
</body>
</html>
Add your div to populate inside of the modal body, and add .modal('show'), so the actual modal window can be shown.
const missingPhotoURL = "URL stack wouldn't let me post";
async function searchShows(query) {
let showRequest = await axios.get(`http://api.tvmaze.com/search/shows?q=${query}`);
let showArray = [];
for(let show of showRequest.data){
let showObj = {
id: show.show.id,
name: show.show.name,
summary: show.show.summary,
image: show.show.image ? show.show.image.medium : missingPhotoURL
};
showArray.push(showObj)
}
console.log(showRequest);
console.log(showArray);
return showArray; //returns array of show objects
}
function populateShows(shows) {
const $showsList = $("#shows-list");
$showsList.empty();
for (let show of shows) {
let $show = $(
`<div class="col-md-6 col-lg-3 Show" data-show-id="${show.id}">
<div class="card" data-show-id="${show.id}">
<div class="card-body" id = "showCard">
<img class="card-img-top" src=${show.image}>
<h5 class="card-title">${show.name}</h5>
<p class="card-text">${show.summary}</p>
<button class="btn btn-outline-primary get-episodes" id="episodeButton" data-bs-toggle="modal" data-bs-target="#episodeModal">Show Episodes</button>
</div>
</div>
</div>
`
);
$showsList.append($show);
$('#episodeModal').modal('show');
}
}
$("#search-form").on("submit", async function handleSearch (evt) {
evt.preventDefault();
let query = $("#search-query").val();
if (!query) return;
$("#episodes-area").hide();
let shows = await searchShows(query);
populateShows(shows);
});
async function getEpisodes(id) {
let episodesRequest = await axios.get(
`http://api.tvmaze.com/shows/${id}/episodes`
);
console.log(episodesRequest);
let episodeArray = [];
for(let episode of episodesRequest.data){
let episodeObj = {
id: episode.id,
name: episode.name,
season: episode.season,
number: episode.number,
};
episodeArray.push(episodeObj);
}
console.log(episodeArray);
return episodeArray;
}
async function populateEpisodes(episodes){
const $episodesModalBody = $('.modalBody')
//$episodesModalBody.empty();
for(let episode of episodes){
let $episodeBody = $(
`<p> ${episode.name} (Season:${episode.season} Episode:${episode.number})</p>`
);
$episodesModalBody.append($episodeBody);
}
}
$('#shows-list').on('click', '.get-episodes', async function episodeClick(e){
let showID = $(e.target).closest('.Show').data('show-id');
let episodes = await getEpisodes(showID);
populateEpisodes(episodes);
})
<!doctype html>
<html>
<head>
<title>TV Maze</title>
<link rel="stylesheet" href="https://unpkg.com/bootstrap/dist/css/bootstrap.css">
</head>
<body>
<h1>TV Maze</h1>
<form class="form-inline" id="search-form">
<input class="form-control" id="search-query" placeholder = 'Show Name'>
<button class="btn btn-primary" type="submit">Go!</button>
</form>
<div class="row mt-3" >
<div class = 'modal fade' id = 'episodeModal' tabindex = '-1'>
<div class = 'modal-dialog modal-dialog-scrollable' >
<div class = 'modal-content'>
<div class = 'modal-header'>
<h5>Episode List:</h5>
</div>
<div class = 'modal-body'>
<div id="shows-list"></div>
</div>
<div class = 'modal-footer'>
<button type="button" class="btn btn-outline-danger" data-bs-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
<script src="http://unpkg.com/jquery"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.6.0/dist/js/bootstrap.min.js"></script>
<script src="http://unpkg.com/axios/dist/axios.js"></script>
<!--script src="tvmaze.js"></script-->
</body>
</html>

TypeError: Cannot set property 'innerHTML' of null while using React.Js

I am new to React.js and I was creating a notes takign website using React.js and Bootstrap. I was saving the notes data in local storage for simplicity but I will upgrade this app to save the notes data in Firebase. However, when I was trying to load the notes from local storage and showing them in the a div element of id 'notes' it gives error that: TypeError: Cannot set property 'innerHTML' of null
I want to run the load notes function after all the html or every thing else is loaded.
When I run this function using button click listener after all the HTML is laoded it works.
The code is:
import React from 'react';
import './Home.css';
function Home() {
const loadNotes = () => {
let notes = localStorage.getItem('notes');
let titles = localStorage.getItem('titles');
let notesObj;
let titlesObj;
if (notes == null) {
notesObj = [];
}
else {
notesObj = JSON.parse(notes);
}
if (titles == null) {
titlesObj = [];
}
else {
titlesObj = JSON.parse(titles);
}
let html = '';
notesObj.forEach(function (element, index) {
html += `<div class="noteCard my-2 mx-2 card" style="width: 18rem;" id = ${index}>
<div class="card-body">
<h5 class="card-title">Note</h5>
<p class="card-text">${element}</p>
<button id = ${index} onclick = 'deleteNote(this.id)' class="btn btn-primary"><i class="fa fa-trash" style="margin-right: 10px;"></i>Delete Note</button>
</div>
</div>`
});
titlesObj.forEach(function (er, i) {
html = html.replace('<h5 class="card-title">Note</h5>', `<h5 class="card-title">${er}</h5>`);
});
let notesElm = document.getElementById('notes');
if (notesObj.length != 0) {
notesElm.innerHTML = html;
}
else {
notesElm.innerHTML = `<h4>Nothing to show here.</h4>`;
}
console.log('Notes shown.')
}
const addNote = () => {
let addTxt = document.getElementById('addTxt');
let notes = localStorage.getItem('notes');
let addTitle = document.getElementById('addTitle');
let titles = localStorage.getItem('titles');
let notesObj;
let titlesObj;
if (notes == null) {
notesObj = [];
}
else {
notesObj = JSON.parse(notes);
}
if (titles == null) {
titlesObj = [];
}
else {
titlesObj = JSON.parse(titles);
}
notesObj.push(addTxt.value);
titlesObj.push(addTitle.value);
localStorage.setItem('notes', JSON.stringify(notesObj));
localStorage.setItem('titles', JSON.stringify(titlesObj));
addTxt.value = '';
addTitle.value = '';
loadNotes();
console.log("Note added.")
}
return (
<div className="home">
<style type="text/css">
{`
.btn {
margin-right: 10px;t
}
.home__mainTitle {
margin-top: 60px;
}
`}
</style>
<div class="container my-3">
<h1 class='home__mainTitle'>Welcome to Magic Notes</h1>
<div class="card">
<div class="card-body" id = 'editor'>
<h5 class="card-title">Add title</h5>
<div class="form-group">
<input className='home__formInput' type="text" class="form-control" id="addTitle" rows="3" placeholder="Title"></input>
</div>
<h5 class="card-title">Add notes</h5>
<div class="form-group">
<textarea class="form-control" id="addTxt" rows="3" placeholder="Notes"></textarea>
</div>
<button class="btn btn-primary" onClick={ addNote } id='addBtn'><i class="fa fa-plus-square"></i>Add Note</button>
<button class="btn btn-primary" id='clearAllBtn'><i class="fa fa-eraser"></i>Clear All</button>
</div>
</div>
<h1 className='home__notesTitle'>Your Notes</h1>
<hr/>
<div id="notes" class="row container-fluid">
{/* <!-- <div class="noteCard my-2 mx-2 card" style="width: 18rem;">
<div class="card-body">
<h5 class="card-title">Note 1</h5>
<p class="card-text"></p>
Delete Note
</div>
</div> --> */}
{ loadNotes() }
</div>
</div>
</div>
);
}
export default Home;
Thanks and sorry from any bad mistakes in code or description of problem.
By trying to access the DOM and set innerHTML directly, you're sort of fighting against some of the general principals of React.
In this specific case, it's failing because the div doesn't actually exist in the DOM when you first try to mutate it.
Take a look at this very partial refactor:
import React, { useEffect, useState } from 'react';
import './Home.css';
function Home() {
const [notes, setNotes] = useState([]);
const [titles, setTitles] = useState([]);
useEffect(() => {
setNotes(JSON.parse(localStorage.getItem('notes')) ?? []);
setTitles(JSON.parse(localStorage.getItem('titles')) ?? []);
},[]);
const addNote = () => {
let addTxt = document.getElementById('addTxt');
let addTitle = document.getElementById('addTitle');
let newTitles = [...titles, addTitle.value];
let newNotes = [...notes, addTxt.value];
localStorage.setItem('notes', JSON.stringify(newNotes));
localStorage.setItem('titles', JSON.stringify(newTitles));
setNotes(newNotes)
setTitles(newTitles)
addTxt.value = '';
addTitle.value = '';
console.log("Note added.")
}
return (
<div className="home">
<style type="text/css">
{`
.btn {
margin-right: 10px;t
}
.home__mainTitle {
margin-top: 60px;
}
`}
</style>
<div class="container my-3">
<h1 class='home__mainTitle'>Welcome to Magic Notes</h1>
<div class="card">
<div class="card-body" id = 'editor'>
<h5 class="card-title">Add title</h5>
<div class="form-group">
<input className='home__formInput' type="text" class="form-control" id="addTitle" rows="3" placeholder="Title"></input>
</div>
<h5 class="card-title">Add notes</h5>
<div class="form-group">
<textarea class="form-control" id="addTxt" rows="3" placeholder="Notes"></textarea>
</div>
<button class="btn btn-primary" onClick={ addNote } id='addBtn'><i class="fa fa-plus-square"></i>Add Note</button>
<button class="btn btn-primary" id='clearAllBtn'><i class="fa fa-eraser"></i>Clear All</button>
</div>
</div>
<h1 className='home__notesTitle'>Your Notes</h1>
<hr/>
<div id="notes" class="row container-fluid">
{notes.map((note,index) => {
return <div class="noteCard my-2 mx-2 card" style={{width: '18rem'}} id={index}>
<div class="card-body">
<h5 class="card-title">{titles[index]}</h5>
<p class="card-text">{note}</p>
<button id={index} onclick='deleteNote(this.id)'
class="btn btn-primary"><i class="fa fa-trash" style={{marginRight: "10px;"}}></i>Delete Note</button>
</div>
</div>
})}
{notes.length === 0 ? <h4>Nothing to show here.</h4> : null}
</div>
</div>
</div>
);
}
export default Home;
Note how I'm using useState to store the notes and titles. Documentation: https://reactjs.org/docs/hooks-state.html
The useEffect is called when the component is mounted and loads the data from localStorage. https://reactjs.org/docs/hooks-effect.html
Then, in the body of the render, instead of calling loadNotes and trying to mutate a DOM that doesn't exist yet, I just map the notes and titles into the rendered content.
Note that this is not a complete refactor yet. For example, you may want to add listeners to your text area to keep track of the content automatically rather than pulling the content with document.getElementById. Also, delete hasn't been implemented yet, the test for localStorage content in useEffect is pretty minimal, etc. But, it's enough to get you started.
This error occurs because loadNotes() is wrapped inside notes div. So, you can check if the notes div is created in first place with if condition.
if (notesElm) {
if (notesObj.length != 0) {
notesElm.innerHTML = html;
}
else {
notesElm.innerHTML = `<h4>Nothing to show here.</h4>`;
}
}
Below is the working code:
import React from 'react';
import './Home.css';
function Home() {
const loadNotes = () => {
let notes = localStorage.getItem('notes');
let titles = localStorage.getItem('titles');
let notesObj;
let titlesObj;
if (notes == null) {
notesObj = [];
}
else {
notesObj = JSON.parse(notes);
}
if (titles == null) {
titlesObj = [];
}
else {
titlesObj = JSON.parse(titles);
}
let html = '';
notesObj.forEach(function (element, index) {
html += `<div class="noteCard my-2 mx-2 card" style="width: 18rem;" id = ${index}>
<div class="card-body">
<h5 class="card-title">Note</h5>
<p class="card-text">${element}</p>
<button id = ${index} onclick = 'deleteNote(this.id)' class="btn btn-primary"><i class="fa fa-trash" style="margin-right: 10px;"></i>Delete Note</button>
</div>
</div>`
});
titlesObj.forEach(function (er, i) {
html = html.replace('<h5 class="card-title">Note</h5>', `<h5 class="card-title">${er}</h5>`);
});
let notesElm = document.getElementById('notes');
if (notesElm) {
if (notesObj.length != 0) {
notesElm.innerHTML = html;
}
else {
notesElm.innerHTML = `<h4>Nothing to show here.</h4>`;
}
}
console.log('Notes shown.')
}
const addNote = () => {
let addTxt = document.getElementById('addTxt');
let notes = localStorage.getItem('notes');
let addTitle = document.getElementById('addTitle');
let titles = localStorage.getItem('titles');
let notesObj;
let titlesObj;
if (notes == null) {
notesObj = [];
}
else {
notesObj = JSON.parse(notes);
}
if (titles == null) {
titlesObj = [];
}
else {
titlesObj = JSON.parse(titles);
}
notesObj.push(addTxt.value);
titlesObj.push(addTitle.value);
localStorage.setItem('notes', JSON.stringify(notesObj));
localStorage.setItem('titles', JSON.stringify(titlesObj));
addTxt.value = '';
addTitle.value = '';
loadNotes();
console.log("Note added.")
}
return (
<div className="home">
<style type="text/css">
{`
.btn {
margin-right: 10px;t
}
.home__mainTitle {
margin-top: 60px;
}
`}
</style>
<div class="container my-3">
<h1 class='home__mainTitle'>Welcome to Magic Notes</h1>
<div class="card">
<div class="card-body" id = 'editor'>
<h5 class="card-title">Add title</h5>
<div class="form-group">
<input className='home__formInput' type="text" class="form-control" id="addTitle" rows="3" placeholder="Title"></input>
</div>
<h5 class="card-title">Add notes</h5>
<div class="form-group">
<textarea class="form-control" id="addTxt" rows="3" placeholder="Notes"></textarea>
</div>
<button class="btn btn-primary" onClick={ addNote } id='addBtn'><i class="fa fa-plus-square"></i>Add Note</button>
<button class="btn btn-primary" id='clearAllBtn'><i class="fa fa-eraser"></i>Clear All</button>
</div>
</div>
<h1 className='home__notesTitle'>Your Notes</h1>
<hr/>
<div id="notes" class="row container-fluid">
{/* <!-- <div class="noteCard my-2 mx-2 card" style="width: 18rem;">
<div class="card-body">
<h5 class="card-title">Note 1</h5>
<p class="card-text"></p>
Delete Note
</div>
</div> --> */}
{ loadNotes() }
</div>
</div>
</div>
);
}
export default Home;

array does not fetch the data in HTML?

I'm trying to make the news list more dynamic , so i tried to make it in array and loop on the categories but unfortunately the function getw () does not fetch the data ?
<nav class="navbar navbar-expand-sm navbar-dark bg-dark mb-5">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler d-lg-none" type="button" data-toggle="collapse" data-target="#collapsibleNavId"
aria-controls="collapsibleNavId" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="collapsibleNavId">
<ul class="navbar-nav ml-auto ml-2 mt-lg-0" id="line">
</ul>
</div>
</nav>
<div class="container">
<div class="row" id="posts-row">
</div>
</div>
java script code
var list = ["General", "Entertainment", "Health", "Science", "Sports", "Technology"];
function getw() {
var lines = "";
for (var i = 0; i < list.length; i++) {
lines += `<li>
<a class='nav-link' href='#'>` + list[i] + `</a>
</li>`
}
document.getElementById("line").innerHTML = lines; (not working i don't know why ?)
}
getdata("general")
var links = document.getElementsByClassName("nav-link");
for (var i = 0; i < links.length; i++) {
links[i].addEventListener("click", function (e) {
var currentCat = e.target.text;
getdata(currentCat.toLowerCase())
})
}
var data;
function getdata(category) {
var httpReq = new XMLHttpRequest();
httpReq.open("GET", "http://newsapi.org/v2/top-headlines?country=eg&category=" + category + "&apiKey=d4f87946d7fc4322be9c2089316d5625");
httpReq.send();
data = [];
httpReq.addEventListener("readystatechange", function () {
if (httpReq.readyState == 4) {
data = JSON.parse(httpReq.response).articles;
Display();
}
})
}
function Display() {
var temp = "";
for (var i = 0; i < data.length; i++) {
temp += `<div class ='col-md-4'>
<div>
<img src=`+ data[i].urlToImage + ` class='img-fluid'>
<h4>`+ data[i].title + `</h4>
<p>`+ data[i].description + `</p>
</div>
</div>`
}
document.getElementById("posts-row").innerHTML = temp;
}
.............................................................................................///////////////////////////////////////////
At least in the code you posted, you are not invoking the getw function.
Try adding getw() at the end of your JavaScript.

Why is collapsible not working for the dynamically created buttons

I am retrieving the data(question) from the database and setting that value to the button.
When I tried to click on the button it should expand the "answer" to that question but it's not happening. I have completely designed rows in the script itself.
I have created a div in HTML and trying to add the rows dynamically to that div in script.
<div class="accordion" id="accordionExample">
<div id="questions">
</div>
</div>
<script>
var store;
var store_count = 0;
var store_row = document.createElement("div");
db.collection("FAQs").orderBy("Priority","asc").get().then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
var qid = doc.id;
var docRef = db.collection("PopopFAQs").doc(qid);
docRef.get().then(function(doc) {
if (doc.exists) {
console.log("Document data:", doc.data());
store_count++;
store = document.createElement("div");
store.setAttribute("class", "card");
store.setAttribute("id", qid);
if(store_count == 1) {
store.innerHTML = `<div class="card-header" id="headingThree">
<h5 class="mb-0">
<button class="btn btn-link no-wrap collapsed btn-faqs" type="button"
data-toggle="collapse" data-target="#`+ doc.data().Priority +`"
aria-expanded="false" aria-controls="collapseThree">
<i class="fa fa-arrow-right"></i> `+ doc.data().Question +`
</button>
</h5>
</div>
<div id="`+ doc.data().Priority +`" class="collapse show"
aria-labelledby="headingThree" data-parent="#accordionExample">
<div class="card-body">`+ doc.data().Answer +`
</div>
</div>`;
}
else {
store.innerHTML = `<div class="card-header" id="headingThree">
<h5 class="mb-0">
<button class="btn btn-link no-wrap collapsed btn-faqs" type="button"
data-toggle="collapse" data-target="#`+ doc.data().Priority +`"
aria-expanded="false" aria-controls="collapseThree">
<i class="fa fa-arrow-right"></i> `+ doc.data().Question +`
</button>
</h5>
</div>
<div id="`+ doc.data().Priority +`" class="collapse"
aria-labelledby="headingThree" data-parent="#accordionExample">
<div class="card-body">`+ doc.data().Answer +`
</div>
</div>`;
}
store_row.append(store);
document.getElementById("questions").innerHTML = store_row.innerHTML;
} else {
console.log("No such document!");
}
}).catch(function(error) {
console.log("Error getting document:", error);
});
});
});
var acc = document.getElementsByClassName("accordion");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].addEventListener("click", function () {
this.classList.toggle("active");
var content = this.parentNode.nextElementSibling;
if (content.style.maxHeight) {
content.style.maxHeight = null;
} else {
content.style.maxHeight = content.scrollHeight + "px";
}
});
}

Categories

Resources