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>
Related
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.
I have created a function that completes a task when the user clicks the complete button, however, I am using a for loop to loop through the array so that it can mark it off.
Currently, what it is doing no matter what complete button I press, it marks off only the first task and not the one I want.
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="../css/main.css">
<script src="js/main.js" defer></script>
<title>To Do Application</title>
</head>
<body>
<div class="form">
<input class ="user-input" type="text">
<input class="date" type="date">
<input class="time" type="time">
<button onclick="addTask()" class="add" id="add">+</button>
</div>
<div class="list"></div>
<!--
<div class="task-content">
<div class="task" data-id="${id}">
<div class="new-task-created">${taskNew}</div>
<label class="due-date">${taskDate}</label>
<label class="due-time">${taskTime}</label>
</div>
<div class="atcion-buttons">
<button onclick="editItem()" class="edit" data-id="${id}">Edit</button>
<button onclick="deleteItem()" class="delete" data-id="${id}">Delete</button>
<button onclick="completeItem()" class="complete" data-id="${id}">Complete</button>
</div>
</div>
-->
</html>
JS
// variables object
const el = {
form: document.querySelector(".form"),
input: document.querySelector(".user-input"),
list: document.querySelector(".list"),
date: document.querySelector(".date"),
time: document.querySelector(".time"),
};
//local storage key
const STORAGE_KEY = "tasks-storage-key";
//Create ID
const createId = () =>
`${Math.floor(Math.random() * 10000)}${new Date().getTime()}`;
//variable of empty array that gets new task
let taskList = JSON.parse(localStorage.getItem(STORAGE_KEY) ?? "[]");
function makeNewTask() {
const data = {
id: createId(),
taskNew: el.input.value,
taskDate: el.date.value,
taskTime: el.time.value,
};
return data
}
//function that creates new tasks with date and time
function display() {
const tasks = document.createElement("div");
data = makeNewTask();
tasks.innerHTML = `
<div class="task-content">
<div class="task" data-id="${data.id}">
<div class="new-task-created">${data.taskNew}</div>
<label class="due-date">${data.taskDate}</label>
<label class="due-time">${data.taskTime}</label>
</div>
<div class="action-buttons">
<button onclick="editItem()" class="edit" data-id="${data.id}">Edit</button>
<button onclick="deleteItem()" class="delete" data-id="${data.id}">Delete</button>
<button onclick="completeItem()" class="complete" data-id="${data.id}">Complete</button>
</div>
</div>`;
taskList.push(tasks);
el.list.appendChild(tasks);
}
//event listner that listens for add button.
function addTask() {
display();
}
//function that stores task list.
function storeList() {
localStorage.setItem(STORAGE_KEY, JSON.stringify(taskList));
}
//function that removes task from array with delete button.
function deleteItem() {
let removeitem = document.querySelector(".task-content");
removeitem.parentNode.removeChild(removeitem);
localStorage.removeItem(STORAGE_KEY);
}
//function that removes stored task when deleted.
//function that that edits tasks with date and time.
function editItem(){
}
//function that that completes task.
function completeItem() {
let taskItem = this.querySelector(".new-task-created");
let dateItem = this.querySelector(".due-date");
let timeItem = this.querySelector(".due-time");
// style..
taskItem.style.textDecoration = "line-through";
dateItem.style.textDecoration = "line-through";
timeItem.style.textDecoration = "line-through";
}
The end result, the complete button should mark off the task via its index and not just the top one.
// variables object
const el = {
form: document.querySelector(".form"),
input: document.querySelector(".user-input"),
list: document.querySelector(".list"),
date: document.querySelector(".date"),
time: document.querySelector(".time"),
};
//local storage key
const STORAGE_KEY = "tasks-storage-key";
//Create ID
const createId = () =>
`${Math.floor(Math.random() * 10000)}${new Date().getTime()}`;
//variable of empty array that gets new task
let taskList = JSON.parse(localStorage.getItem(STORAGE_KEY) ?? "[]");
function makeNewTask() {
const data = {
id: createId(),
taskNew: el.input.value,
taskDate: el.date.value,
taskTime: el.time.value,
};
return data
}
//function that creates new tasks with date and time
function display() {
const tasks = document.createElement("div");
data = makeNewTask();
tasks.innerHTML = `
<div class="task-content">
<div class="task" data-id="${data.id}">
<div class="new-task-created">${data.taskNew}</div>
<label class="due-date">${data.taskDate}</label>
<label class="due-time">${data.taskTime}</label>
</div>
<div class="action-buttons">
<button onclick="editItem(event)" class="edit" data-id="${data.id}">Edit</button>
<button onclick="deleteItem(event)" class="delete" data-id="${data.id}">Delete</button>
<button onclick="completeItem(event)" class="complete" data-id="${data.id}">Complete</button>
</div>
</div>`;
taskList.push(tasks);
el.list.appendChild(tasks);
}
//event listner that listens for add button.
function addTask() {
display();
}
//function that stores task list.
function storeList() {
localStorage.setItem(STORAGE_KEY, JSON.stringify(taskList));
}
//function that removes task from array with delete button.
function deleteItem() {
let removeitem = document.querySelector(".task-content");
removeitem.parentNode.removeChild(removeitem);
localStorage.removeItem(STORAGE_KEY);
}
//function that removes stored task when deleted.
//function that that edits tasks with date and time.
function editItem(){
}
//function that that completes task.
function completeItem(event) {
const element = event.target.closest('.task-content')
console.log(element)
let taskItem = element.querySelector(".new-task-created");
let dateItem = element.querySelector(".due-date");
let timeItem = element.querySelector(".due-time");
// style..
taskItem.style.textDecoration = "line-through";
dateItem.style.textDecoration = "line-through";
timeItem.style.textDecoration = "line-through";
}
<!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="../css/main.css">
<script src="js/main.js" defer></script>
<title>To Do Application</title>
</head>
<body>
<div class="form">
<input class ="user-input" type="text">
<input class="date" type="date">
<input class="time" type="time">
<button onclick="addTask()" class="add" id="add">+</button>
</div>
<div class="list"></div>
<!--
<div class="task-content">
<div class="task" data-id="${id}">
<div class="new-task-created">${taskNew}</div>
<label class="due-date">${taskDate}</label>
<label class="due-time">${taskTime}</label>
</div>
<div class="atcion-buttons">
<button onclick="editItem()" class="edit" data-id="${id}">Edit</button>
<button onclick="deleteItem()" class="delete" data-id="${id}">Delete</button>
<button onclick="completeItem()" class="complete" data-id="${id}">Complete</button>
</div>
</div>
-->
</body>
</html>
I am trying to create a function that add user in javascript.
Here is my code snippets from js file and html file:
function input() {
document.getElementById("name").style.visibility = "visible";
document.getElementById("id").style.visibility = "visible";
document.getElementById("number").style.visibility = "visible";
document.getElementById("search").style.visibility = "visible";
}
function addUser(list) {
var text = "";
var inputs = document.querySelectorAll("input[type=text]");
for (var i = 0; i < inputs.length; i++) {
text += inputs[i].value;
}
var list = document.createElement("div");
var node = document.createTextNode(text);
list.appendChild(node);
document.getElementById("usersList").appendChild(list);
}
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<div class="contact-container">
<div class="navbar">
<ul id="menuList">
<li>
<img src="https://img.icons8.com/ios-filled/50/000000/contact-card.png"/>
</li>
<li>View</li>
<li onclick="input()">
Add
</li>
</ul>
</div>
<div class="users">
<input type="text" id="name" placeholder="Name"/>
<input type="text" id="id" placeholder="Id"/>
<input type="text" id="number" placeholder="Number"/>
<button type="submit" id="search" onclick="addUser()">
<svg...> </svg>
</button>
<div id="usersList"></div>
</div>
</div>
</body>
</html>
How can I make styling when add user just like the one I had in html file?
Here is my project:
Thank you so much!!!!!!
Put newlines between each value from the inputs, and set the style of the DIV to white-space: pre.
function input() {
document.getElementById("name").style.visibility = "visible";
document.getElementById("id").style.visibility = "visible";
document.getElementById("number").style.visibility = "visible";
document.getElementById("search").style.visibility = "visible";
}
function addUser(list) {
var text = "";
var inputs = document.querySelectorAll("input[type=text]");
for (var i = 0; i < inputs.length; i++) {
text += inputs[i].value + '\n';
}
var list = document.createElement("div");
var node = document.createTextNode(text);
list.appendChild(node);
document.getElementById("usersList").appendChild(list);
}
#usersList div {
white-space: pre;
}
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<div class="contact-container">
<div class="navbar">
<ul id="menuList">
<li>
<img src="https://img.icons8.com/ios-filled/50/000000/contact-card.png"/>
</li>
<li>View</li>
<li onclick="input()">
Add
</li>
</ul>
</div>
<div class="users">
<input type="text" id="name" placeholder="Name"/>
<input type="text" id="id" placeholder="Id"/>
<input type="text" id="number" placeholder="Number"/>
<button type="submit" id="search" onclick="addUser()">
<svg...> </svg>
</button>
<div id="usersList"></div>
</div>
</div>
</body>
</html>
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>
How to error proof JavaScript from item list by entering the same item or no item. Please help me guys of been researching for days StackOverFlow is my last hope. Any Help will be appreciated.`Thanks guys
var app = angular.module('myApp',[]);
app.controller('SportController', function($scope) {
$scope.newItem;
//List Sport
$scope.sports = ['Football', 'Basketball', 'Hockey', 'Soccer'];
//Remove Sport
$scope.addItem = function(){
$scope.sports.push($scope.newItem);
$scope.newItem = '';
}
//Remove Sport
$scope.removeItem = function(item){
var idx = $scope.sports.indexOf(item);
$scope.sports.splice(idx,1);
}
});
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<link rel="stylesheet" href="css/style.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script src="js/app.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller='SportController'>
<h1>Sport List</h1>
<div>
<form ng-submit="addItem()">
<div>
<input type="text" ng-model="newItem" placeholder"Add Sport"/>
<button type="submit">Save</button>
</div>
</form>
</div>
<p> {{ newItem }}</p>
<div>
<h4>Sports {{ sports.length }}</h4>
<table>
<tr ng-repeat="spor in sports">
<td>{{spor}}</td>
<td>
<button ng-click="removeItem(spor)">×</button>
</td>
</tr>
</table>
</div>
<!--End of div--->
</body>
</html>
Block the UI from being able to submit.
Or use a simple if check...
$scope.addItem = function(item){
//blank item
if(!item) return; //or display an alert
//item already exists
if($scope.sports.indexOf(item) > -1) return; //or display a different alert
$scope.sports.push(item);
$scope.newItem = null;
}