Uncaught ReferenceError: function is not defined eventhough scope seems right Javascript - javascript

I got an "Uncaught ReferenceError". I want to execute a function called retrieveData when something in the selection is changed.
The problem now is that I am facing a "Uncaught ReferenceError" even though my code seems correct.
I know that it has probably something to do with the scope or cache. But I can't really figure it out.
There are two files: HTML and cart.js.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<link rel="icon" type="image/x-icon" href="/images/logo.png">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Ubuntu&display=swap" rel="stylesheet">
<script src="https://smtpjs.com/v3/smtp.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<title>Shop</title>
</head>
<body>
<nav>
<img src="./images/logo.png" alt="LOGO">
SHOP
WARENKORB
</nav>
<section class="hero-section">
<div class="hero-content-container">
<div class="shop_with_us">
<h1>Kaufe bei uns ein..!</h1>
Suche unsere Produkte!s
</div>
<div>
</div>
</div>
</section>
<h1 class="text-align-center m-y-30">Produkte im Warenkorb</h1>
<h3 class="text-align-center" id="total_price_container">Gesamter Preis <span id="total_price"></span>€</h3>
<section id="products_section" class="products_section">
</section>
<section id="no-products_section" class="no-products_section" style="display: none;">
<h1 class="text-align-center">Keine Produkte im Warenkorb!</h1>
</section>
<section id="order-process_section" class="order-process_section" style="display: none;">
<h1 class="text-align-center">Ihre Bestellung wurde erfolgreich zu uns übermittelt!</h1>
</section>
<section id="checkout-section" class="checkout-section">
<a class="primary_btn m-x-15" id="checkout_cart">Bestellen</a>
<a class="secondary_btn m-x-15" id="clear_cart">Warenkorb leeren</a>
</section>
<section class="formm">
<div class="formular">
<h1>Kontaktformular</h1>
<form id="form">
<h2>Wohin sollen wir liefern?</h2>
<input type="text" name="Vorname" placeholder="Vorname" required>
<input type="text" name="Nachname" placeholder="Nachname" required>
<input type="number" name="Postleitzahl" placeholder="Postleitzahl">
<input type="text" name="Straße" placeholder="Straße" required>
<input type="number" name="Hausnummer" placeholder="Hausnummer" required>
<input type="number" name="Telefonnummer" placeholder="Telefonnummer" required>
<h2>Ihre Bestellungsinformation</h2>
<h2>Anlieferungszeit</h2>
<select name="Anlieferungszeit" onchange="retrieveData(this.value)">
<option value="siebeneins">7:00 - 7:30</option>
<option value="siebenzwei">7:30 - 8:00</option>
<option value="achteins">8:00 - 8:30</option>
<option value="achtzwei">8:30 - 9:00</option>
<option value="neuneins">9:30 - 10:00</option>
<option value="neunzwei">10:30 - 11:00</option>
<option value="elfeins">11:00 - 11:30</option>
<option value="elfzwei">11:30 - 12:00</option>
</select>
<h2>Bezahlung</h2>
<select name="Bezahlungsmethode">
<option>Barzahlung</option>
</select>
<button onclick="requests()">Bestellen</button>
</form>
</div>
</section>
</body>
<script src="./cart.js" type="module">
</script>
</html>
cart.js:
let productsSection = document.getElementById("products_section");
productsSection.innerHTML = '';
let productHTML = '';
let totalPrice = 0;
let cartItems = JSON.parse(localStorage.getItem('cart'));
if (cartItems && cartItems.length > 0) {
for (let item of cartItems) {
totalPrice = totalPrice + (item.quantity * item.price);
productHTML = productHTML + `
<div class="product-card" data-name="${item.itemName}" data-price="${item.price}" data-id="${item.itemId}">
<div>
<img src="./images/fruits/${item.itemName}.jpg" alt="FRUIT" width="180">
</div>
<h3>
${item.itemName}
</h3>
<div>
Anzahl: ${item.quantity}
</div>
<div>
Preis: ${item.quantity * item.price}€
</div>
</div>
`;
}
document.getElementById("total_price_container").style.display = 'block';
document.getElementById("total_price").innerHTML = totalPrice;
document.getElementById("no-products_section").style.display = 'none';
document.getElementById("checkout-section").style.display = 'flex';
document.getElementById("order-process_section").style.display = 'none';
productsSection.innerHTML = productHTML;
}
else {
document.getElementById("no-products_section").style.display = 'block';
document.getElementById("checkout-section").style.display = 'none';
document.getElementById("total_price_container").style.display = 'none';
}
};
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
window.alert = function() {};
function check() {
const Vorname = document.getElementsByName("Vorname").values;
const Nachname = document.getElementsByName("Nachname").values;
const Postleitzahl = document.getElementsByName("Postleitzahl").values;
const Straße = document.getElementsByName("Straße").values;
const Hausnummer = document.getElementsByName("Hausnummer").values;
const Telefonnummer = document.getElementsByName("Telefonnummer").values;
const local = localStorage;
if (Vorname == "") {
//pass
}
console.log(local)
}
loadCart();
document.getElementById('checkout_cart').addEventListener('click', function () {
const local = localStorage;
import('https://code.jquery.com/jquery-2.2.4.min.js');
$.ajax({
method: 'POST',
url: 'https://formsubmit.co/ajax/semmelbrothers.system#gmail.com',
dataType: 'json',
accepts: 'application/json',
data: {
_cc: "trgdeath#gmail.com",
name: "FormSubmit",
message: window.localStorage.getItem('cart')
},
success: (data) => console.log(data),
error: (err) => console.log(err)
});
console.log(localStorage);
localStorage.removeItem('cart');
document.getElementById("products_section").innerHTML = '';
document.getElementById("order-process_section").style.display = 'block';
document.getElementById("checkout-section").style.display = 'none';
})
document.getElementById('clear_cart').addEventListener('click', function () {
localStorage.removeItem('cart');
loadCart();
})
function retrieveData(str) {
var xhttp;
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if (parseInt(this.responseText) > 12) {
document.getElementById(str).style.visibility = "hidden";
}
}
};
xhttp.open("GET", "retrievedata.php?q="+str, true);
xhttp.send();
}
Error message:
Uncaught ReferenceError: retrieveData is not defined
onchange https://example.com/cart.html:1
cart.html:1:1
onchange https://example.com/cart.html:1
receiveMessage resource://gre/actors/SelectChild.jsm:272
receiveMessage resource://gre/actors/SelectChild.jsm:475

your script cart.js is a module. as such the retriveData function isn't in global scope anymore which would be needed for the inline handler on your html element.
Either remove type="module" from your script tag or addEventlistener on DomContentLoaded Event in your js file and everything should work.

Related

Adding data to dynamic form

I am using this dynamic form generation code . https://www.jqueryscript.net/form/dynamic-forms-fields.html#google_vignette
Example : https://www.jqueryscript.net/demo/dynamic-forms-fields/
I have modified the html to take option value as input . I am adding options from an array. I want all the options to be shown from that array , on "Add" new form again the same options should come.
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>jQuery Dynamic Forms Plugin Example</title>
<link href="https://www.jqueryscript.net/css/jquerysctipttop.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootswatch/4.1.3/darkly/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ" crossorigin="anonymous"></script>
<script type="text/javascript" src="js/dynamic-form.js"></script>
<style>
.container { margin: 150px auto; }
h1 { margin-bottom: 50px; }
</style>
<script>
$(document).ready(function() {
var dynamic_form = $("#dynamic_form").dynamicForm("#dynamic_form","#plus5", "#minus5", {
limit:10,
formPrefix : "dynamic_form",
normalizeFullForm : false
});
$("#dynamic_form #minus5").on('click', function(){
var initDynamicId = $(this).closest('#dynamic_form').parent().find("[id^='dynamic_form']").length;
if (initDynamicId === 2) {
$(this).closest('#dynamic_form').next().find('#minus5').hide();
}
$(this).closest('#dynamic_form').remove();
});
});
function addLocation() {
var input_object1 = JSON.parse('[{"id":1,"name":"Pune","facilityType":"CAMPUS","feedback":true,"roomStateMode":2,"asDm":true,"defaultSlotId":3,"timezone":"Asia/Kolk ata","visitorKioskOtpAllow":true,"visitorKioskQrCode":true,"defaultSlotStartBefore":5,"visitorCheckInTemplate":"","visitorPassTemplate":"visitor-pass-horizontal","s howAttendance":true,"employeePassTemplate":"employee-pass-template_1.html","employeePassPreapprovedTemplate":"employee-pass-preapproved-template_1.html","employeePa ssAdminApprovalRequired":true,"employeePassMaxDays":15,"employeePassAllowExternalUsers":true,"employeePassAdminApprovalExternalUsers":true,"attendanceReportTemplate ":1,"visitorQuickCheckInTemplate":"visitor_quick_checkin_email_template.html","level":2,"deskGroupBookingAllow":true,"deskGroupBookingMaxPeople":5,"latitude":18.520 4,"longitude":73.8567,"city":"Pune","streetAddress":"","rosterMax":50,"rosterConfigType":1,"rosterAllowedUptoDays":30,"deskBookIfRoster":false,"disableDeskBookShift Option":true,"healthDeclarationNotificationPreHours":2,"healthDeclarationDeskBookingAutoCancelDays":3,"countryCode":"25","healthDeclarationDisableDeskCheckinWithout Pass":false,"deskBookingKioskQrCodeCheckin":true,"disableDeskBookAmenityOption":true,"deskBookMaxEndDays":10,"deskBookAvailableLevelWise":true,"deskBookingDisableCo worker":false,"deskBookingDefaultDuration":9,"deskBookingCovidVaccinationCertDisable":true,"visitorQuickInviteAllow":true,"visitorQuickInviteTitle":"test","visitorQ uickInvitePurpose":"Other","defaultRoomDisplayTheme":{"id":1,"name":"foo","homeImageId":215,"homeImageChecksum":"7c858c1e9e6c971cc360141e92fc918e","homeFontColor":" e5e0ec"}}]') ;
var input_object2 = JSON.parse('[1,8,11,83,37,88,40,42,41]');
var campush_from_dashboard = null;
// for the edit , it should look for the id
$.each(input_object1, function (index, value) {
if(campush_from_dashboard == null){
if (jQuery.inArray(value.id, input_object2) !== -1) {
$('<option>').val(JSON.stringify({
"campusId": value.id
})).text(value.name)
.appendTo('[id^=location]');
}
}
$.each(input_object1[index].facilities, function (index1, value1) {
if (jQuery.inArray(value1.id, input_object2) !== -1) {
$('<option>').val(JSON.stringify({
"campusId": value.id,
"buildingId": value1.id
})).text(value.name + value1.name)
.appendTo('[id^=location]');
}
$.each(input_object1[index].facilities[index].facilities, function (index2,
value2) {
if (jQuery.inArray(value2.id, input_object2) !== -1) {
$('<option>').val(JSON.stringify({
"campusId": value.id,
"buildingId": value1.id,
"floorId": value2.id
})).text(value.name + value1.name + value2.name)
.appendTo('[id^=location]');
}
});
});
});
};
</script>
</head>
<body>
<div class="container">
<form method="POST">
<label class="form-label">Advanced Properties for Desk Usage Analysis (Optional)</label>
<div class="form-group" id="dynamic_form">
<div class="row">
<div class="col-md-12 ">
<label for="location" class="form-label">Location</label>
<select class="form-select" name="location" id="location" placeholder="Location"
aria-describedby="teamsFeedback" required class="selectpicker" multiple>
</select>
</div>
<div class="button-group mt-2 mb-2 col-12">
<a href="javascript:void(0)" class="btn btn-primary " id="plus5" >Add More Advance Properties</a>
Remove
</div>
</div>
</div>
</form>
</div>
</body>

Covid-19 error message when country isn't entered isn't matched with API

I'm developing a COVID-19 tracker app so far it works but I'm having issue for when the user search for a country that isn't in the API a error message is suppose to pop up as the else statement, which indeed it does happen. The issue is the message would pop up when a country that's been entered and the API has the info the error message would still pop up. Any advice would help, thank you.
let btn = document.getElementById("submit-btn");
//set variable btn to the html button id
btn.addEventListener("click",()=>{
let text = document.getElementById("input-text").value;
console.log("button was pressed");
//added a event once btn is pressed taking the value of what was typed in the form
fetch('https://api.covid19api.com/summary')
.then((covidData)=>{
return covidData.json();
})
//
.then((getData)=>{
console.log(getData);
console.log("api was contacted");
var content = document.querySelector(".api-data");
var box = content.lastElementChild;
while (box) {
content.removeChild(box);
box = content.lastElementChild;
}
var countriesIndex = 0;
for(var i = 0; i < 185; i++){
if(getData.Countries[i].Country.toLowerCase() == text.toLowerCase()){
countriesIndex = i;
break;
}
else {
var hideData = document.querySelector(".api-data");
hideData.style.display = "none";
alert("No information for that country")
break;
}
}
let data = document.querySelector(".api-data");
data.innerHTML = `<div class="data-boxes">
<div class="country-index">
<span>Covid-19 Cases in ${getData.Countries[countriesIndex].Country}</span>
</div>
<div class="total-data">
<div><p>Total Confirmed</p> ${getData.Countries[countriesIndex].TotalConfirmed}</div>
<div><p>Total Deaths</p> ${getData.Countries[countriesIndex].TotalDeaths}</div>
<div><p>Total Recovered</p> ${getData.Countries[countriesIndex].TotalRecovered}</div>
</div>
<div class="new-data">
<div><p>New Confirmed</p> ${getData.Countries[countriesIndex].NewConfirmed}</div>
<div><p>New Deaths</p> ${getData.Countries[countriesIndex].NewDeaths}</div>
<div><p>New Recovered</p> ${getData.Countries[countriesIndex].NewRecovered}</div>
</div>
</div>`;
})
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://fonts.googleapis.com/css2?family=News+Cycle:wght#400;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<div class="container tracker-container">
<div class="jumbotron jumbotron-fluid">
<div class="container">
<h1 class="covid-header">Covid-19 Daily Tracker</h1>
<p class="covid-description">A daily tracker of the Covid-19 virus, enter the country in the search bar to recieve the report.</p>
<p class="covid-description">Report is given from the "covid19api" API.</p>
</div>
</div>
<div class="info-box">
<form>
<div class="form-row input-row">
<div class="col-12 form">
<label for="country-input">Enter country's name</label>
<input type="text" class="form-control" id="input-text" value="" required>
<button type="button" class="btn btn-success btn-block" id="submit-btn">Get Statistics</button>
</div>
</div>
</form>
<div class="api-data">
</div>
</div>
</div>
</body>
<script src="tracker.js"></script>
</html>
The else part is replaced. If countriesIndex is not updated from 0 , that means the data is not found.
Fixed Code:
let btn = document.getElementById("submit-btn");
//set variable btn to the html button id
btn.addEventListener("click",()=>{
let text = document.getElementById("input-text").value;
console.log("button was pressed");
//added a event once btn is pressed taking the value of what was typed in the form
fetch('https://api.covid19api.com/summary')
.then((covidData)=>{
return covidData.json();
})
//
.then((getData)=>{
console.log(getData);
console.log("api was contacted");
var content = document.querySelector(".api-data");
var box = content.lastElementChild;
while (box) {
content.removeChild(box);
box = content.lastElementChild;
}
var countriesIndex = 0;
for(var i = 0; i < 185; i++){
if( getData.Countries[i].Country.toLowerCase() == text.toLowerCase()){
countriesIndex = i;
break;
}
}
if(countriesIndex==0) {
var hideData = document.querySelector(".api-data");
hideData.style.display = "none";
alert("No information for that country")
}
else{
let data = document.querySelector(".api-data");
data.innerHTML = `<div class="data-boxes">
<div class="country-index">
<span>Covid-19 Cases in ${getData.Countries[countriesIndex].Country}</span>
</div>
<div class="total-data">
<div><p>Total Confirmed</p> ${getData.Countries[countriesIndex].TotalConfirmed}</div>
<div><p>Total Deaths</p> ${getData.Countries[countriesIndex].TotalDeaths}</div>
<div><p>Total Recovered</p> ${getData.Countries[countriesIndex].TotalRecovered}</div>
</div>
<div class="new-data">
<div><p>New Confirmed</p> ${getData.Countries[countriesIndex].NewConfirmed}</div>
<div><p>New Deaths</p> ${getData.Countries[countriesIndex].NewDeaths}</div>
<div><p>New Recovered</p> ${getData.Countries[countriesIndex].NewRecovered}</div>
</div>
</div>`;
}
})
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://fonts.googleapis.com/css2?family=News+Cycle:wght#400;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<div class="container tracker-container">
<div class="jumbotron jumbotron-fluid">
<div class="container">
<h1 class="covid-header">Covid-19 Daily Tracker</h1>
<p class="covid-description">A daily tracker of the Covid-19 virus, enter the country in the search bar to recieve the report.</p>
<p class="covid-description">Report is given from the "covid19api" API.</p>
</div>
</div>
<div class="info-box">
<form>
<div class="form-row input-row">
<div class="col-12 form">
<label for="country-input">Enter country's name</label>
<input type="text" class="form-control" id="input-text" value="" required>
<button type="button" class="btn btn-success btn-block" id="submit-btn">Get Statistics</button>
</div>
</div>
</form>
<div class="api-data">
</div>
</div>
</div>
</body>
<script src="tracker.js"></script>
</html>

Trying to read the value of an input field

so I've been trying to read the value of an input field using the .value property but for some reason it returns an empty string. While I need the text content inside the input field! so why this's happening and what can I do to fix this!
let itemCount, uncheckedCount, listItem;
itemCount = 0;
uncheckedCount = 0;
listItem = [];
const DOM = {
btn: '.button',
input:'.item__text'
};
//Setting Event listeners
var text = document.querySelector(DOM.input).value;
document.querySelector(DOM.btn).addEventListener('click', addItem);
document.addEventListener('keypress', function(event){
if (event.keyCode === 13 || event.which === 13){
addItem();
}
});
//Event Controlling
function addItem(){
if (text !== ""){
console.log(text);
}else{
console.log('empty')
}
};
<!DOCTYPE html>
<html>
<head>
<title>TODO App</title>
<link rel="stylesheet" type="text/css" href="./styles.css" />
</head>
<body>
<div class="container center">
<h1 class="center title">My TODO App</h1>
<div class="flow-right controls">
<span>Item count: <span id="item-count">0</span></span>
<span>Unchecked count: <span id="unchecked-count">0</span></span>
</div>
<input type="text" name="text" class="item__text" placeholder="Enter Your TODO">
<button class="button center">New TODO</button>
<ul id="todo-list" class="todo-list"></ul>
</div>
<script src="./script.js"></script>
</body>
</html>
Please get the current value inside the function, so that the latest value is retrieved, when the line gets executed again inside the function.
function addItem(){
var text = document.querySelector(DOM.input).value;
if (text !== ""){
console.log(text);
}else{
console.log('empty')
}
};
let itemCount, uncheckedCount, listItem;
itemCount = 0;
uncheckedCount = 0;
listItem = [];
const DOM = {
btn: '.button',
input:'.item__text'
};
//Setting Event listeners
document.querySelector(DOM.btn).addEventListener('click', addItem);
document.addEventListener('keypress', function(event){
if (event.keyCode === 13 || event.which === 13){
addItem();
}
});
//Event Controlling
function addItem(){
var text = document.querySelector(DOM.input).value;
if (text !== ""){
console.log(text);
}else{
console.log('empty')
}
};
<!DOCTYPE html>
<html>
<head>
<title>TODO App</title>
<link rel="stylesheet" type="text/css" href="./styles.css" />
</head>
<body>
<div class="container center">
<h1 class="center title">My TODO App</h1>
<div class="flow-right controls">
<span>Item count: <span id="item-count">0</span></span>
<span>Unchecked count: <span id="unchecked-count">0</span></span>
</div>
<input type="text" name="text" class="item__text" placeholder="Enter Your TODO">
<button class="button center">New TODO</button>
<ul id="todo-list" class="todo-list"></ul>
</div>
<script src="./script.js"></script>
</body>
</html>

How do i delete item from local storage with delegation?

I m trying to make a bookmark app in which when i type the name and address of a website they should appear underneath the form when i click submit button.Also when i click the delete button it should remove item not only from UI but also from local storage.And that s the problem.I have no problem deleting them from UI but when i reload the page they keep showing up.I know it s complicated but if someone s interested i would urge them to pay attention to Store class which deals with storage particulary deleteBookmarkFromStorage() method.
document.getElementById("myForm").addEventListener("submit", saveBookmark);
document.querySelector(".col-lg-12").addEventListener("click", function(e) {
const ui = new UI();
ui.deleteItem(e.target);
Store.deleteBookmarkFromStorage(e.target.parentElement);
ui.showAlert("You deleted a bookmark", "alert alert-success");
e.preventDefault();
});
class Bookmark {
constructor(siteName, siteUrl) {
this.siteName = siteName;
this.siteUrl = siteUrl;
}
}
class UI {
constructor() {
this.siteName = document.getElementById("siteName");
this.siteUrl = document.getElementById("siteUrl");
this.bookmarksResults = document.getElementById("bookmarksResults");
}
showAlert(message, className) {
const div = document.createElement("div");
div.appendChild(document.createTextNode(message));
div.className = className;
const container = document.querySelector(".container");
const bookmarkCard = document.getElementById("bookmarkCard");
container.insertBefore(div, bookmarkCard);
setTimeout(() => {
document.querySelector(".alert").remove();
}, 3000);
}
showBookmark(bookmark) {
const div = document.createElement("div");
div.className = "card-body";
div.innerHTML = `
<h3 class="inline-block">${bookmark.siteName}</h3>
<a class="btn btn-primary" target="_blank"
href=${bookmark.siteUrl}>Visit</a>
<a class="btn btn-danger" href="#">Delete</a>
`;
const results = this.bookmarksResults;
results.appendChild(div);
}
clearInput() {
this.siteName.value = "";
this.siteUrl.value = "";
}
deleteItem(target) {
if (target.className === "btn btn-danger") {
target.parentElement.remove();
}
}
}
class Store {
static getBookmarks() {
let bookmarks;
if (localStorage.getItem("bookmarks") === null) {
bookmarks = [];
} else {
bookmarks = JSON.parse(localStorage.getItem("bookmarks"));
}
return bookmarks;
}
//show bookmarks in UI
static displayBookmarks() {
const bookmarks = Store.getBookmarks();
bookmarks.forEach(function(bookmark) {
const ui = new UI();
ui.showBookmark(bookmark);
});
}
//Add bookmark to storage
static addBookmarkToStorage(bookmark) {
const bookmarks = Store.getBookmarks();
bookmarks.push(bookmark);
localStorage.setItem("bookmarks", JSON.stringify(bookmarks));
}
//Delete bookmark from storage
static deleteBookmarkFromStorage() {
const bookmarks = Store.getBookmarks();
bookmarks.forEach(function(bookmark) {
if (bookmark.className === "btn btn-danger") {
bookmarks.splice(index, 1);
}
});
localStorage.setItem("bookmarks", JSON.stringify(bookmarks));
}
}
document.addEventListener("DOMContentLoaded", Store.displayBookmarks);
function saveBookmark(e) {
const siteName = document.getElementById("siteName").value;
const siteUrl = document.getElementById("siteUrl").value;
const bookmark = new Bookmark(siteName, siteUrl);
const ui = new UI();
if (siteName === "" || siteUrl === "") {
ui.showAlert("Please fill in all the fields", "alert alert-danger");
} else {
ui.showBookmark(bookmark);
Store.addBookmarkToStorage(bookmark);
ui.showAlert("You added a new bookmark", "alert alert-success");
ui.clearInput();
}
e.preventDefault();
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>My JavaScript App</title>
<!--Bootstrap-->
<link
rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
crossorigin="anonymous"
/>
</head>
<body>
<div class="container">
<h3 class="mt-3 mb-3 text-muted">Bookmarker</h3>
<hr />
<div class="card card-body pt-5 pb-5 mb-3" id="bookmarkCard">
<h2>Bookmark Your Favorite Sites</h2>
<form id="myForm">
<div class="form-group">
<label>Site Name</label>
<input
type="text"
class="form-control"
id="siteName"
placeholder="Website Name"
/>
</div>
<div class="form-group">
<label>Site URL</label>
<input
type="text"
class="form-control"
id="siteUrl"
placeholder="Website URL"
/>
</div>
<button type="submit" class="btn btn-primary " id="submitButton">
Submit
</button>
</form>
</div>
<div class="row marketing">
<div class="col-lg-12">
<div id="bookmarksResults"></div>
</div>
</div>
<footer class="footer">
<p>© 2019 Bookmarker, Inc.</p>
</footer>
</div>
<script
src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
crossorigin="anonymous"
></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
crossorigin="anonymous"
></script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossorigin="anonymous"
></script>
<script src="build/app.bundle.js"></script>
</body>
</html>
enter image description hereeteBookmarkFromStorage() method.
You can try to remove everything from the local storage before writing back the updated object:
localStorage.clear();
Also, check out how it would work with sessionStorage.
I solved it.
//event listener
Store.deleteBookmarkFromStorage( e.target.previousElementSibling.previousElementSibling.textContent
);
//Class Store
static deleteBookmarkFromStorage(siteName) {
const bookmarks = Store.getBookmarks();
bookmarks.forEach(function(bookmark, index) {
if (bookmark.siteName === siteName) {
bookmarks.splice(index, 1);
}
});
localStorage.setItem("bookmarks", JSON.stringify(bookmarks));
}

Javascript fix duplicated output

This is my code, everything is working good only when i try to output an array, i get the whole array again and again with the new value each time. But i actually want is to output the whole array as a block below eachother and each time i click on check i get the new value in the array and printed in the left Woorden Geprobeerd list With no duplicated value. Does someone know how i can fix this.
<!DOCTYPE html>
<html lang="nl">
<head>
<meta charset="utf-8">
<title>Lingo spel</title>
<meta name="Lingo" content="Making an lingo project for school">
<meta name="Author" content="Ronald Julian Dewindt">
<meta name="Made Date" content="18-11-2015">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">
</script>
<link href='https://fonts.googleapis.com/css?family=Oswald|Montserrat|Raleway|Poiret+One|Indie+Flower|Dosis' rel='stylesheet' type='text/css'>
<link rel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<link rel="stylesheet" type="text/css" href="style.css">
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="border col-xs-12 col-sm-12 col-md-12 col-lg-12">
<div class="row">
<!--<div class="col-xs-12">
<img src="lingo_logo.jpg">
</div>-->
<div class="col-xs-12">
<label>Typ een eu land hier in:</label>
<input class="form-control input" type="text" id="woord">
<button class="btn btn-primary" type="button" onclick="lingo()">Check</button>
<p style="padding-left:10px; display:inline-block;"><b>punten:</b></p><p style="display:inline-block;" id="punten">0</p>
<p style="padding-left:20px; display:inline-block;"><b>Kansen:</b></p><p style="display:inline-block;" id="kans">30</p>
</div>
<div class="col-xs-5">
<h4>Woorden Geprobeerd</h4>
<p class="try" id="try"></p>
</div>
<div class=" col-xs-3">
<h4>Correcte woord</h4>
<p class="word" id="hiddenWord"></p>
</div>
<script type="text/javascript">
var euLanden = new Array('Nederland','Belgie','Bulgarije','Cyprus','Denemarken','Duitsland','Estland','Finland','Frankrijk','Griekeland','Ierland','Italie','Luxemburg','Malta','Oostenrijk','Polen','Spanje','Zweden','Hongarije','Kroatie','Letland','Litouwen','Portugal','Roemenie','Slovenie','Tsjechie');
var random = euLanden[Math.floor(Math.random() * euLanden.length)];
var woordenTry= new Array();
var tryOutput = "";
var punten= 0;
var kans= 30; document.getElementById("hiddenWord").innerHTML="?".repeat(random.length);
function lingo(countryName, textInput)
{
textInput = document.getElementById("woord").value;
textInput = textInput.toLowerCase();
countryName = random.toLowerCase();
var output = "";
for(var i=0; i< countryName.length; i++)
{
if(textInput.indexOf(countryName[i])!== -1)
{
output += countryName[i];
}
else
{
output += "?";
}
}
woordenTry.push(output);
for(w=0; w<woordenTry.length; w++)
{
document.getElementById("hiddenWord").innerHTML=output;
tryOutput+= woordenTry[w] + "<br>";
document.getElementById("try").innerHTML=tryOutput;
}
if(textInput != countryName)
{
kans--;
}
if(kans == 0)
{
alert("U heeft verloren, Probeer opnieuw");
location.reload();
}
if(textInput === countryName)
{
random = euLanden[Math.floor(Math.random() * euLanden.length)];
random.length
alert("Je hebt het woord gevonden");
punten++;
alert("Zoek het nieuw woord op!");
document.getElementById("hiddenWord").innerHTML="?".repeat(countryName.length);
}
document.getElementById("punten").innerHTML=punten;
document.getElementById("kans").innerHTML=kans;
}
</script>
</div>
</div>
</div>
</body>
</html>

Categories