Session storage value showing null - javascript

I keep on getting null every time I try to store values in Section B and C but works fine for A. I can't seem to find where the issue is. I am trying to have a user's info display on a different page based on the section he chooses. If the user chooses section B for example I would want to let the user know on the next page that he/she has ordered a seat in Section B and whatever the available seat is along with the name and price. After the boarding pass is displayed on the next page, I want the array to change from having 5 seats to 4 and keep this array updated everytime a new person signs up.
index.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">
<title>Document</title>
<script src = "airplane.js"></script>
</head>
<style>
</style>
<body>
<h1>Welcome To Air France</h1>
<h2>Choose your seat section here</h2>
<h3>Section A</h3>
<p>Price:</p>
<div id = "Section1Price"></div>
<div id = "Section1"></div>
<form action = "bookingPage.html" method="post">
<p>Enter your full name to book in this section:</p>
<input id="clientNameA" type="text" size="25" height="25">
<input id = "bookSeatA" type="button" onclick="location.href='bookingPage.html';" value="Book a Seat in Section A" />
</form>
<h3>Section B</h3>
<p>Price:</p>
<div id = "Section2Price"></div>
<div id = "Section2"></div>
<form action = "bookingPage.html" method="post">
<p>Enter your full name to book in this section:</p>
<input id="clientNameB" type="text" size="25" height="25">
<input id = "bookSeatB" type = "button" onclick="location.href='bookingPage.html';" value = "Book a Seat in Section B">
</form>
<h3>Section C</h3>
<p>Price:</p>
<div id = "Section3Price"></div>
<div id = "Section3"></div>
<form action = "bookingPage.html" method="post">
<p>Enter your full name to book in this section:</p>
<input id="clientNameC" type="text" size="25" height="25">
<input id = "bookSeatC" type = "button" onclick="location.href='bookingPage.html';" value = "Book a Seat in Section C">
</form>
</body>
</html>
airplane.js
function start()
{
var price1;
price1 = Math.random() * (200 - 100) + 100;
price1 = price1.toFixed(2);
var price2 = (Math.random() * (300 - 100) + 100).toFixed(2);
var price3 = (Math.random() * (300 - 100) + 100).toFixed(2);
var priceArray = [price1, price2, price3];
var sectionASeats = [];
var sectionBSeats = [];
var sectionCSeats = [];
for (var k = 0; k < 5; k++)
{
sectionASeats[k] = 0;
sectionBSeats[k] = 0;
sectionCSeats[k] = 0;
}
var buttonA = document.getElementById( "bookSeatA" );
buttonA.addEventListener( "click", function() {bookSeat(sectionASeats)}, false );
buttonA.addEventListener("click",function(){handleSubmitA(priceArray[0],sectionASeats,"A")}, false );
var buttonB = document.getElementById( "bookSeatB" );
buttonB.addEventListener( "click", function() {bookSeat(sectionBSeats)}, false );
buttonB.addEventListener("click",function(){handleSubmitB(priceArray[1]),sectionBSeats,"B"}, false );
var buttonC = document.getElementById( "bookSeatC" );
buttonC.addEventListener( "click", function() {bookSeat(sectionCSeats)}, false );
buttonC.addEventListener("click",function(){handleSubmitC(priceArray[2]),sectionCSeats,"C"}, false );
var result1 = "";
var result2 = "" ;
var result3 = "" ;
result1 += checkSection(sectionASeats, "A" );
result2 += checkSection(sectionBSeats, "B" );
result3 += checkSection(sectionCSeats, "C" );
priceArray.sort(function(a,b) {return a-b});
document.getElementById("Section1Price").innerHTML = "$" + priceArray[0];
document.getElementById("Section1").innerHTML = result1;
document.getElementById("Section2Price").innerHTML = "$" + priceArray[1];
document.getElementById("Section2").innerHTML = result2;
document.getElementById("Section3Price").innerHTML ="$" + priceArray[2];
document.getElementById("Section3").innerHTML = result3;
}
function sectionSeatNum (array)
{
for (var i = 0; i < array.length;i++)
{
if (array[i] == 1)
{
return i+1;
}
}
}
function handleSubmitA(priceForA,array,section)
{
const name = document.getElementById("clientNameA").value;
var seatNumber = sectionSeatNum(array);
sessionStorage.setItem("ARRAY", JSON.stringify(array));
sessionStorage.setItem("SECTION", section);
sessionStorage.setItem("SEATNUM", seatNumber);
sessionStorage.setItem("NAME", name);
sessionStorage.setItem("PRICE", priceForA);
return;
}
function handleSubmitB(priceForB,array,section)
{
const name = document.getElementById("clientNameB").value;
var seatNumber = sectionSeatNum(array);
sessionStorage.setItem("ARRAY", JSON.stringify(array));
sessionStorage.setItem("SECTION", section);
sessionStorage.setItem("SEATNUM", seatNumber);
sessionStorage.setItem("NAME", name);
sessionStorage.setItem("PRICE", priceForB);
return;
}
function handleSubmitC(priceForC,array,section)
{
const name = document.getElementById("clientNameC").value;
var seatNumber = sectionSeatNum(array);
sessionStorage.setItem("ARRAY", JSON.stringify(array));
sessionStorage.setItem("SECTION", section);
sessionStorage.setItem("SEATNUM", seatNumber);
sessionStorage.setItem("NAME", name);
sessionStorage.setItem("PRICE", priceForC);
return;
}
function bookSeat(array)
{
for(var i = 0; i < array.length; i++)
{
if(array[i] == 0)
{
array[i] = 1;
break;
}
}
}
function checkSection(array, section)
{
var result;
var check = true;
var emptyCounter = 0;
var takenCounter = 0;
for (var i = 0;i<array.length;i++)
{
if(array[i] == 0)
{
emptyCounter++;
}
else{
takenCounter++;
}
}
if(takenCounter == array.length)
{
check = false;
result = "<p>There are no seats available in Section " + section + ".</p>";
}
else{
check = true;
result = "<p>There are " + emptyCounter + " seats available in Section " + section + ".</p>";
}
return result;
}
window.addEventListener("load", start,false);
bookingPage.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">
<title>Document</title>
<script src = "booking.js"></script>
</head>
<body>
<h1>Thank you for choosing Air France</h1>
<h2>Here is your boarding pass</h2>
<h3 id="booking-name"></h3>
<form action="index.html" method="get">
<input id = "backToHome" type="button" onclick="location.href='index.html';" value="Return to Homepage">
</form>
</body>
</html>
booking.js
function start()
{
const name = sessionStorage.getItem("NAME");
const price = sessionStorage.getItem("PRICE");
const arrayBookings = JSON.parse(sessionStorage.getItem("ARRAY"));
const section = sessionStorage.getItem("SECTION");
var seatNum = sessionStorage.getItem("SEATNUM")
var result = "";
result += "<p> Thank you " +name+ " for flying with us. Here is your boarding pass.</p>";
result += "<p> Name: " + name + "</p>";
result += "<p> Section: "+ section + "</p>";
result += "Price: $"+price;
result += "<p>Seat number: "+seatNum+ "</p>";
// result += "<p>"+arrayBookings+"</p>";
document.getElementById("booking-name").innerHTML = result;
}
window.addEventListener("load", start, false);

You have typo here
buttonB.addEventListener("click",function(){handleSubmitB(priceArray[1]),sectionBSeats,"B"}, false );
while you want to have
buttonB.addEventListener("click",function(){handleSubmitB(priceArray[1],sectionBSeats,"B")}, false );
Session C is the same error.

Related

Using PokeAPI to fetch data. Can't figure out why span element is not updating

So I'm using the PokeAPI to fetch the name of a Pokemon, then shuffling that name, and the user is supposed to guess what it is in the input. If they don't know then they can click the next button and it reshuffles a new mon. If they guess right they can press the same next button for a new mon. Each time they guess right the score increases by 1. That's working but I cant figure out why the out of/total games span isn't updating as well. Please excuse my terrible attempt at JS I'm very new if you can help me make my code look better that would be great.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<link rel="stylesheet" href="style.css" />
<title>Who's that Pkmn?</title>
</head>
<body>
<header>
<h1>Who's that Pokemon?!</h1>
</header>
<div id="jumble">?????</div>
<div class="container">
<input id="guess" type="text" placeholder="enter pkmn name" />
<button id="submit" class="btn" type="submit">go</button>
<button id="next" class="btn">next</button>
<p id="msg">unshuffle the letters</p>
</div>
<div id="scorekeepers">
<p>Score: <span id="score">0</span>
out of: <span id="gamesPlayed">0</span></p>
</div>
<script src="script.js"></script>
</body>
</html>
let jumbledName = document.querySelector("#jumble");
let guessInput = document.querySelector('#guess')
let submitButton = document.querySelector('#submit')
let nextButton=document.querySelector('#next')
let messageDisplay = document.querySelector('#msg')
let score = document.querySelector('#score')
let gamesPlayed = document.querySelector('#gamesPlayed')
score = 0;
gamesPlayed = 0;
let getPokemonName = function() {
fetch(`https://pokeapi.co/api/v2/pokemon/${Math.floor(Math.random()*151+1)}/`)
.then(function(response) {
return response.json();
})
.then(function(data) {
const pokeName = data.name;
const pokeNameJumbled = pokeName.shuffle();
displayInfomation(pokeName, pokeNameJumbled);
});
};
getPokemonName();
guessInput.value=''
// pokeNameJumbled=''
const displayInfomation = function(name, jumbledName) {
pokeName = name;
pokeNameJumbled = jumbledName;
jumble.textContent = jumbledName;
};
const displayMessage = function(message) {
document.querySelector("#msg").textContent = message;
};
const checkName = function () {
document.querySelector("#guess").textContent = guessInput;
const guess = document.querySelector("#guess").value.toLowerCase();
if (!guess) {
displayMessage("No guess entered!");
} else if (guess === pokeName) {
displayMessage(`Thats correct! It's ${pokeName}!`)
score++
document.querySelector("#score").textContent = score;
guessInput.value=''
} else if (guess != pokeName) {
displayMessage(`Wrong!`);
document.querySelector("#gamesPlayed").textContent = gamesPlayed;
}
};
submitButton.addEventListener('click', checkName)
nextButton.addEventListener('click',getPokemonName)
String.prototype.shuffle = function() {
var a = this.split(""),
n = a.length;
for (var i = n - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
return a.join("");
};

JS get random value from array and update array

I need your help on this!
I'm generating an array which corresponds to a question number.
var arrayCharge = [];
for (var i = 2; i <= 45; i++) {
arrayCharge.push(i);
}
then I use this number to append the corresponding question, answer then click.
Then I'm getting a new value from the array like this
const randomQ = arrayCharge;
const random = Math.floor(Math.random() * randomQ.length);
It works and a new question is charged but the array is still the same.
I've tried this
var remQ = arrayCharge.indexOf(randomQ[random]);
arrayCharge.splice(remQ,1);
But It doesn't work ;-(
Thanks a lot for your help.
Nicolas
Here is the entire code to help comprehension! sorry for that, I should have done it from the begining.
<!DOCTYPE HTML>
<!--
Hyperspace by HTML5 UP
html5up.net | #ajlkn
Free for personal and commercial use under the CCA 3.0 license (html5up.net/license)
-->
<html>
<head>
<title>Repérez vos messages contraignants - Quiz</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
<link rel="stylesheet" href="assets/css/main.css" />
<noscript>
<link rel="stylesheet" href="assets/css/noscript.css" /></noscript>
</head>
<body class="is-preload">
<!-- Sidebar -->
<!-- <section id="sidebar">
</section> -->
<!-- Wrapper -->
<div id="wrapper">
<!-- Intro -->
<section id="intro" class="wrapper style1 fullscreen fade-up">
<div class="inner">
<header>
<button id="start">Commencer</button>
<p> </p>
</header>
<form action="" method="post">
<p id="Qnum"></p>
<p id="Q" data-qnumber="" data-type=""></p>
<section id="answer">
<input type="submit" id="1" name="R1" value="Non">
<input type="submit" id="2" name="R2" value="Parfois">
<input type="submit" id="3" name="R3" value="Souvent">
<input type="submit" id="4" name="R4" value="Oui">
</section>
</form>
</div>
</section>
<!-- Footer -->
<!-- Scripts -->
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/jquery.scrollex.min.js"></script>
<script src="assets/js/jquery.scrolly.min.js"></script>
<script src="assets/js/browser.min.js"></script>
<script src="assets/js/breakpoints.min.js"></script>
<script src="assets/js/util.js"></script>
<script src="assets/js/main.js"></script>
<script>
$(document).ready(function() {
if (localStorage.getItem("clic") >= 45) {
console.log('45');
sessionStorage.clear();
localStorage.clear();
}
var Q1 = [1, "My first question", "FP"];
var Q2 = [2, "My second question", "SP"];
var Q3 = [3, "My third question", "SE"];
var Q4 = [4, "My foutrh question", "DP"];
var Q5 = [5, "My fifth question", "FP"];
//etc... until Q45
if (sessionStorage.getItem("FP") == null) {
$("form").attr("action", "driversV2.php");
$("#answer").hide();
$("#start").click(function() {
$("#Qnum").append(1+" / 45");
$("#Q").append(Q1[1]).attr("data-qnumber", Q1[0]).attr("data-type", Q1[2]);
$("#answer").show();
$("header").hide();
var pageType = $("#Q").attr("data-type");
$("input").click(function() {
var reponse = this.id;
sessionStorage.setItem(pageType, reponse);
localStorage.setItem("clic", 1);
});
});
} else {
$("header").hide();
var clicNum = parseInt(localStorage.getItem("clic"));
var QNumber = clicNum + 1;
var arrayCharge = [];
for (var i = 2; i <= 45; i++) {
arrayCharge.push(i);
}
const randomQ = arrayChargeNew;
const random = Math.floor(Math.random() * randomQ.length);
console.log('valeur random new = '+randomQ[random]);
var QCharge = "Q" + randomQ[random];
var Charge = eval(QCharge);
localStorage.setItem("random",randomQ[random]);
$("#Qnum").append(QNumber+" / 45");
$("#Q").append(Charge[1]).attr("data-qnumber", Charge[0]).attr("data-type", Charge[2]);
//création de la variable du type de question
var pageType = $("#Q").attr("data-type");
//alert(sessionStorage.getItem(pageType));
if (localStorage.getItem("clic") < 44) {
$("form").attr("action", "driversV2.php");
if (sessionStorage.getItem(pageType) != null) {
var x = parseInt(sessionStorage.getItem(pageType));
$("input").click(function() {
var reponse = parseInt(this.id);
var addition = reponse + x;
sessionStorage.setItem(pageType, addition);
var clic = parseInt(localStorage.getItem("clic"));
localStorage.setItem("clic", clic + 1);
});
} else {
$("input").click(function() {
var reponse = this.id;
sessionStorage.setItem(pageType, reponse);
var clic = parseInt(localStorage.getItem("clic"));
localStorage.setItem("clic", clic + 1);
});
}
} else {
$("form").attr("action", "driversResultat.php");
if (sessionStorage.getItem(pageType) != null) {
var x = parseInt(sessionStorage.getItem(pageType));
$("input").click(function() {
var reponse = parseInt(this.id);
var addition = reponse + x;
sessionStorage.setItem(pageType, addition);
var clic = parseInt(localStorage.getItem("clic"));
localStorage.setItem("clic", clic + 1);
});
} else {
$("input").click(function() {
var reponse = this.id;
sessionStorage.setItem(pageType, reponse);
var clic = parseInt(localStorage.getItem("clic"));
localStorage.setItem("clic", clic + 1);
});
}
}
}
});
</script>
</body>
</html>
Nicolas, this is the sort of thing you should end up with:
// From my library js file
// returns a random number in the given range
function getRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// Variables for objects that need to be available throughout
let availableQuestions = [];
let rnd = 0;
let counter = 0;
// Populate the question array - how this is done depends on where the question data comes from
function createQuestions() {
availableQuestions.length = 0;
for (let i = 1; i <= 10; i++) {
availableQuestions.push({"questionnumber": i, "question": "Text for question " + i});
}
}
// Pick a random question and display that to the user
function getRandomQuestion() {
let osQuestions = availableQuestions.length;
let qnElement = document.getElementById("questionnumber");
let qElement = document.getElementById("question");
let sButton = document.getElementById("submit");
let rButton = document.getElementById("restart");
// If there are no more questions, stop
if (osQuestions == 0) {
qnElement.innerHTML = "Finished!";
qElement.innerHTML = "";
sButton.style.display = "none";
rButton.style.display = "inline";
} else {
// display a sequential question number rather than the actual question number
counter++;
rnd = getRandomNumber(0, osQuestions - 1);
let thisQuestion = availableQuestions[rnd];
qnElement.innerHTML = "Question: " + counter + " (Actually question: " + thisQuestion.questionnumber + ")";
qElement.innerHTML = thisQuestion.question;
}
}
// Process the user's answer and remove the question from the array
function submitAnswer() {
// ALSO Add in what needs to be done to update backend database etc when the user clicks submit
availableQuestions.splice(rnd, 1);
getRandomQuestion();
}
// Reset everything - for testing purposes only
function restart() {
let qnElement = document.getElementById("questionnumber");
let qElement = document.getElementById("question");
let sButton = document.getElementById("submit");
let rButton = document.getElementById("restart");
qnElement.innerHTML = "";
qElement.innerHTML = "";
sButton.style.display = "inline";
rButton.style.display = "none";
// Reset the displayed question number counter
counter = 0;
createQuestions();
getRandomQuestion();
}
// Needed to populate the array and display the first question
function runsetup() {
createQuestions();
getRandomQuestion();
}
window.onload = runsetup;
<div id="questionnumber"></div>
<hr>
<div id="question"></div>
<button id="submit" onclick="submitAnswer();">Submit</button>
<button id="restart" onclick="restart();" style="display:none;">Restart</button>
I've included a counter variable so that the user does't see the actual question number - just 1, 2, 3 etc but I've shown the actual question number so that you can see it working
Nicolas, this is what I think you should be doing:
// Create the array in whatever way you need to
var arrayCharge = [];
for (var i = 2; i <= 45; i++) {
arrayCharge.push({"questionnumber": i, "question": "Text of question " + i});
}
// Just confirm the length of the array - should be 44
console.log(arrayCharge.length);
// Generate a random number based on the length of the array
var rnd = Math.floor(Math.random() * arrayCharge.length);
// Get the question at the randomly generated index number
let thisQuestion = arrayCharge[rnd];
// Check that we have a random question
console.log(thisQuestion.questionnumber);
console.log(thisQuestion.question)
// Present the question to the user on the page
// The user completes question and clicks "Submit"
// Now remove the question, using the SAME index number
arrayCharge.splice(rnd,1);
// Check that the array has lost an entry - the size should now be 43
console.log(arrayCharge.length);

Unable to call JavaScript method based on button element "id"

I am following a tutorial from Head First Javascript. In the tutorial, the showBlogs() method is called via the following html code
HTML button
<input type="button" id="showall" value="Show all blog entries" onclick="showBlogs();" />
function showBlogs(numberOfEntries){
//sort the blogs in reverse chronological order (most recent first)
blogs.sort(function(blog1, blog2){
return blog2.date - blog1.date;
})
//set the number of entires if non specified
if(!numberOfEntries){
numberOfEntries = blogs.length;
}
//set blog entries
var currenetBlog = 0; blogListHTML = "";
while(currenetBlog < blogs.length && currenetBlog < numberOfEntries){
blogListHTML += blogs[currenetBlog].toHTML(currenetBlog % 2 == 0);
currenetBlog++;
}
//display blog entries
blogsDOM.innerHTML = blogListHTML;
}
However, when I create another button and access it via javascript and call the same method with the event handler - nothing happens.
Button
<button type="button" id="showAllBlogs">Show All Posts</button>
Access Button within Javascript
const showBlogsButton = document.getElementById('showAllBlogs');
Call the showBlogs method
showBlogsButton.addEventListener('click', showBlogs);
I did try creating another function say 'foo()' and I called foo() with the new button and I was able to invoke the method. But when I call the showBlogs() method, nothing happens.
JAVASCRIPT CODE
`
//dom elements
const blogsDOM = document.getElementById('blog');
const query = document.getElementById('searchInput');
const searchButton = document.getElementById('searchButton');
const showBlogsButton = document.getElementById('showAllBlogs');
// Constructor
function Blog(body, dateString){
this.body = body;
this.date = new Date(dateString);
this.toString = function(){
return this.date.getMonth() + '/' + this.date.getDate() + '/' + this.date.getFullYear() + '/' +
this.body;
};
this.toHTML = function(highlight){
var htmlPost = "";
//determine to highlight post
htmlPost += highlight ? "<p style='background-color: #EEEEEE'>" : "<p>";
//generate formatted html
htmlPost += this.date.getMonth() + '/' + this.date.getDate() + '/' + this.date.getFullYear() + '/' +
this.body + "</p>";
//return html
return htmlPost;
};
this.containsText = function(text){
return this.body.toLowerCase().indexOf(text.toLowerCase()) > -1;
};
}
//Array of blogs
var blogs = [
new Blog("Got the new cube I ordered", "01/25/1986"),
new Blog("This new cube works just fine", "02/22/2000"),
new Blog("This is going to be the third one", "03/23/2005"),
new Blog("This is the final one", "03/21/2020")
]
blogs.sort(function(blog1, blog2){ return blog2.date - blog1.date; })
function getDaysBetweenDates(date1, date2){
var daysBetween = (date2 - date1) / (1000 * 60 * 60 * 24);
return Math.round(daysBetween);
}
function formatDate(date){
return date.getDay() + '/' + date.getMonth() + '/' + date.getYear();
}
function searchForPost(event){
let matchingBlogs = [];
event.preventDefault();
const searchQuery = query.value;
blogs.forEach(blog =>{
if(blog.body.toLowerCase().indexOf(searchQuery.toLowerCase()) > -1){
matchingBlogs.push(blog);
}
} )
showBlogs(matchingBlogs.length, matchingBlogs);
}
//show list of blog
function showBlogs(numberOfEntries, blogsToShow = blogs){
//sort the blogs in reverse chronological order (most recent first)
blogs.sort(function(blog1, blog2){
return blog2.date - blog1.date;
})
//set the number of entires if non specified
if(!numberOfEntries){
numberOfEntries = blogs.length;
}
//set blog entries
var currenetBlog = 0; blogListHTML = "";
while(currenetBlog < blogs.length && currenetBlog < numberOfEntries){
blogListHTML += blogs[currenetBlog].toHTML(currenetBlog % 2 == 0);
currenetBlog++;
}
//display blog entries
blogsDOM.innerHTML = blogListHTML;
}
searchButton.addEventListener('click', searchForPost);
showBlogsButton.addEventListener('click', showBlogs);`
HTML CODE
`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Blog</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h3>Youtube - the Blog for Cube puzzlers</h3>
<div class="search-container">
<input type="text" id="searchInput" placeholder="Search for a blog"/>
<button type="button" id="searchButton">Search the blog</button>
</div>
<div id="blog"></div>
<input type="button" id="showall" value="Show all blog entries" onclick="showBlogs();" />
<button type="button" id="showAllBlogs">Show All Posts</button>
<script src="script.js"></script>
</body>
</html>`

Choosing an item from HTML collection

I'm trying to select the elements(lis)that are pushed into my array(todos its a ul)..
when the function (nu) is called it creates a new li and stores it in an HTML Collection...
I want to be able to select those li for styling.
var input = document.querySelector("#input");
var todos = [];
var list = document.getElementById("list");
var lis = document.getElementsByTagName("li")
var btns = document.querySelectorAll("button")
function nu() {
input.addEventListener("change", function () {
todos.push(input.value)
list.innerHTML += "<li>" + input.value + "</li>"
input.value = ""
})
return list;
}
function alo() {
for (i = 0; i < todos.length; i++) {
lis.item(i).addEventListener("click", function () {
alert("alo")
})
}
}
function disp() {
todos.forEach(i => {
list.innerHTML += "<li>" + i + "</li>"
});
return list;
}
disp()
nu()
I tried to do this
function silly() {
for (i = 0; i < lis.length; i++) {
lis[i].addEventListener("click", function () {
alert("working")
})
}
}
still doesn't work :/..
here is my html
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="new.css">
<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>New To-do!</title>
</head>
<body>
<div class="container">
<h1>MY TO-DO</h1>
<input type="type" placeholder="New TO-DO" id="input">
<ul id="list">
</ul>
</div>
<script src="todo.js" type="text/javascript"></script>
</body>
</html>
And this is the output, I want to style those todos.!
JSFiddle : https://jsfiddle.net/cytjae3z/
The function you created actually works, I think your problem comes from the fact that you weren't able to call it in the right place, that being in the input.addEventListener. Here is a working example :
var input = document.querySelector("#input");
var todos = [];
var list = document.getElementById("list");
var lis = document.getElementsByTagName("li")
var btns = document.querySelectorAll("button")
function nu() {
input.addEventListener("change", function() {
todos.push(input.value)
list.innerHTML += "<li>" + input.value + "</li>"
input.value = ""
silly()
})
return list;
}
function alo() {
for (i = 0; i < todos.length; i++) {
lis.item(i).addEventListener("click", function() {
alert("alo")
})
}
}
function disp() {
todos.forEach(i => {
list.innerHTML += "<li>" + i + "</li>"
});
return list;
}
function silly() {
for (i = 0; i < lis.length; i++) {
lis[i].addEventListener("click", function() {
this.style.backgroundColor = "#" + ((1 << 24) * Math.random() | 0).toString(16)
})
}
}
disp()
nu()
<div class="container">
<h1>MY TO-DO</h1>
<input type="type" placeholder="New TO-DO" id="input">
<ul id="list">
</ul>
</div>

javascript Uncaught TypeError: .indexOf is not a function

This is the javascript code:
/**
* Created by Alejandro on 25/02/2016.
*/
var aantalKoppels = 2;
function setup(){
var btnToevoegen = document.getElementById("btnToevoegen");
btnToevoegen.addEventListener("click", koppelToevoegen);
var btnReplace = document.getElementById("btnReplace");
btnReplace.addEventListener("click", update);
}
function koppelToevoegen() {
var parameterDataKoppel = document.createElement("div");
var labelParameter = document.createElement("label");
labelParameter.innerHTML = "Parameter:";
labelParameter.setAttribute("for", "parameter" + aantalKoppels);
var parameter = document.createElement("input");
parameter.id = "parameter" + aantalKoppels;
parameter.setAttribute("type", "text");
var labelData = document.createElement("label");
labelData.innerHTML = "Data:";
labelData.setAttribute("for", "data" + aantalKoppels);
var data = document.createElement("input");
data.id = "data" + aantalKoppels;
data.setAttribute("type", "text");
parameterDataKoppel.appendChild(labelParameter);
parameterDataKoppel.appendChild(parameter);
parameterDataKoppel.appendChild(labelData);
parameterDataKoppel.appendChild(data);
var parameterDataKoppels = document.getElementById("parameterDataKoppels");
parameterDataKoppels.appendChild(parameterDataKoppel);
aantalKoppels++;
}
function update() {
var parameterDataKoppels = [];
var rangnummerKoppel = 1;
for(var i = 0; i < aantalKoppels - 1; i++) {
var parameter = (document.getElementById("parameter" + rangnummerKoppel)).value;
var data = (document.getElementById("data" + rangnummerKoppel)).value;
parameterDataKoppels[i] = [parameter.trim(), data.trim()];
rangnummerKoppel++;
}
var template = document.getElementById("template");
vervangAlles(template, parameterDataKoppels);
}
function vervangAlles(template, parameterDataKoppels) {
for(var i = 0; i < parameterDataKoppels.length; i++) {
var result = vervang(template, parameterDataKoppels[i][0], parameterDataKoppels[i][1]);
template = result;
}
var output = document.getElementById("txtOutput");
output.innerHTML = template;
return template;
}
function vervang(template, parameter, data) {
var result = template.substring(0, template.indexOf(parameter)) + data;
var i = template.indexOf(parameter) + parameter.length;
while(template.indexOf(parameter, i) !== -1) {
var indexVolgende = template.indexOf(parameter, i);
result += (template.substring(i, indexVolgende)) + data;
i = indexVolgende + parameter.length;
}
result += template.substring(i, template.length);
return result;
}
window.addEventListener("load",setup,false);
This code should take a template (String), parameters (String word out of text) and data (String) as input to then replace al the parameters in the text by the String data. I do get an error which I can't figure out at the first line in the last function:
Uncaught TypeError: template.indexOf is not a functionvervang # ReplaceFunction.js:61vervangAlles # ReplaceFunction.js:52update # ReplaceFunction.js:47
this is the html code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script type="text/javascript" charset="utf-8" src="../scripts/ReplaceFunction.js"></script>
<title>ReplaceFunction</title>
</head>
<body>
<div>
<label for="template">Template:</label>
<input id="template" type="text" />
</div>
<div id="parameterDataKoppels">
<div>
<label for="parameter1">Parameter:</label>
<input id="parameter1" type="text" />
<label for="data1">Data:</label>
<input id="data1" type="text" />
</div>
</div>
<input id="btnToevoegen" type="button" value="Koppel toevoegen" />
<input id="btnReplace" type="button" value="Replace" />
<p id="txtOutput">geen output</p>
</body>
</html>
I hope somebody knows why I get this error.
It seems like your 'update' should be
function update() {
var parameterDataKoppels = [];
var rangnummerKoppel = 1;
for(var i = 0; i < aantalKoppels - 1; i++) {
var parameter = (document.getElementById("parameter" + rangnummerKoppel)).value;
var data = (document.getElementById("data" + rangnummerKoppel)).value;
parameterDataKoppels[i] = [parameter.trim(), data.trim()];
rangnummerKoppel++;
}
//var template = document.getElementById("template");
var template = document.getElementById("template").value;
vervangAlles(template, parameterDataKoppels);
}

Categories

Resources