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

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>`

Related

Session storage value showing null

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.

Is there a way I could read and update values from html attributes in node js?

I want to use the date-holidays npm package to check for holidays between two given dates and also a custom function to check for weekends and then subtract the two from the number of days between the two dates so that I can return the number of available workdays.
So far I have created the functions using hardcoded dates and it works perfectly in the console but I don't know how to read the date-values from the HTML file using onchange() and use them to get the remaining days then and then update the value of the remaining days on the HTML page before submitting the form. I tried using document.getElementbyId() but found out that node.js doesn't support DOM.
How can I get around this?
The code:
var Holidays = require('date-holidays')
var hd = new Holidays()
var countries = hd.getCountries() // get supported countries
hd.init('KE') // get kenyan Holidays for the current year
function getFormated_StartDate(){
var start_hol = new Date("11/30/2021");
var dd = String(start_hol.getDate()).padStart(2, '0');
var mm = String(start_hol.getMonth()+1).padStart(2, '0');
var yyy= start_hol.getFullYear();
start_hol = new Date(mm + '/' + dd + '/' + yyy);
return start_hol;
}
function getFormated_EndDate(){
var end_hol = new Date("12/28/2021");
var dd = String(end_hol.getDate()).padStart(2, '0');
var mm = String(end_hol.getMonth()+1).padStart(2, '0');
var yyy= end_hol.getFullYear();
end_hol = new Date(mm + '/' + dd + '/' + yyy);
return end_hol;
}
function getTimeDifference(){
var a = getFormated_StartDate();
var b = getFormated_EndDate();
var Diff_in_tym = b.getTime() - a.getTime();
return Diff_in_tym;
}
function getDifferenceInDays(){
var i = getTimeDifference();
var Diff_in_days = i / (1000 * 3600 * 24);
return Diff_in_days;
}
function getWeekendsAndHolidays(){
var overall_days = 0;
var start = getFormated_StartDate();
var end = getFormated_EndDate();
for (var d = new Date(start); d <= end; d.setDate(d.getDate() + 1)) {
var check_hol = hd.isHoliday(d);
// both || holiday_only || weekend_only
if( ( (check_hol != false) && (d.getDay() == 6 || d.getDay() == 0) ) || (check_hol != false) || (d.getDay() == 6 || d.getDay() == 0) ){
overall_days = overall_days + 1;
// console.log(d.toDateString());
}
}
return overall_days;
}
function getSundaysAndHolidays(){
var total_days = 0;
var Start = getFormated_StartDate();
var End = getFormated_EndDate();
for (var d = new Date(Start); d <= End; d.setDate(d.getDate() + 1)) {
var check_hol = hd.isHoliday(d);
// both || holiday_only || sundays_only
if( ( (check_hol != false) && (d.getDay() == 0) ) || (check_hol != false) || ( d.getDay() == 0) ){
total_days = total_days + 1;
// console.log(d.toDateString());
}
}
return total_days;
}
function getWorkingDaysIncludingSundays(){
var sundaysAndHolidays = getSundaysAndHolidays();
var DifferenceInDays = getDifferenceInDays();
var workingDaysIncludingSundays = DifferenceInDays - sundaysAndHolidays;
return workingDaysIncludingSundays;
}
function getWorkingDays(){
var weekendsAndHolidays = getWeekendsAndHolidays();
var differenceInDays = getDifferenceInDays();
var workingDays = differenceInDays - weekendsAndHolidays;
return workingDays;
}
var z = getWorkingDays();
var Z = getWorkingDaysIncludingSundays();
console.log(z + "\n" + Z);
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="./redefine.js"></script>
<title>Hello, world!</title>
</head>
<body>
<h3 class="container display-5">
<p class="text-info">Working Days </p>
</h3>
<h3></h3>
<section class="container" style="padding-top: 5%; padding-left: 5%;">
<form NAME="myForm" Action="" METHOD="GET" >
<div class="form-row">
<label for="start_day" class="form-group">Enter the Start Date: <br>
<input type="date" name="start_day" id="start" required pattern="\d{4}-\d{2}-\d{2}"> <br>
<span class="validity"></span>
</label>
<label for="end_day" class="form-group">Enter the End Date:<br>
<input type="date" name="end_day" id="end" required pattern="\d{4}-\d{2}-\d{2}"><br>
<span class="validity"></span>
</label>
</div>
<button type="button" class="btn btn-primary" NAME="button" Value="Calculate" onClick="getWorkingDays(this.form)">
Calculate</button>
<br>
<br>
<div class="form-group row">
<label for="results" class="col-sm-2 col-form-label">Available workdays :</label>
<div class="col-sm-10">
<input type="text" readonly class="form-control-plaintext" id="static" value="0">
</div>
</div>
</form>
</section>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</body>
</html>
So, it sounds like you don't understand that your nodejs server runs in a completely separate network and computer from the HTML page and its Javascript which runs in the browser (on the end-user's computer). The two are completely separate. This is what is known as the client/server architecture. The server cannot directly access the running HTML page in the browser.
To use the change event in your HTML page to validate a value on your server, you would need to send an Ajax call (an http network request) to your server with the new data and ask your server if that data is valid. Your web page will then get the result back from that web page and can then act accordingly.
To support the Ajax call for this particular validation call, you would create a new route on your nodejs server specifically for this operation.
Or, if what you want to do in the change event does not need to talk to your server, then you can just add Javascript directly to your web page, get the new value from the change event and then (from entirely within the web page), decide what modifications or checks you want to do in the current web page.

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);

Dynamic information extraaction

I'm working on a code for extract information from an .json file and print it on a website. I achived all but now I have a problem, the data is showing only 1 result, it create all boxes/places for the other information but only the first "box" have information.
<head>
<!-- Title and Extern files -->
<title>SSL Checker</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script type="text/javascript" src="js/db.json"></script>
</head>
<body>
<div id="header">
<h2>SSL Checker</h2>
</div>
<div id="form">
<p>Introduce the URL:</p>
<input id="txtbx" type="text">
<button type="submit" onClick="agregar_caja()">Send</button>
<div id="inf">
<p type="text" id="hl1"></p>
<p type="text" id="hl2"></p>
</div>
<script>
//Extract
console.log(MyJSON[1].url)
var cajas = 2
var boxsaved = MyJSON.length
fnc = function(info) {
hey = document.getElementById("hl1").innerHTML = info.url;
}
//box creator
sm = function agregar_caja() {
document.getElementById("inf").innerHTML += "<p type=text id='hl" + new String(cajas + 1) + "'><br>"
cajas = cajas + 1
}
//Loops
for (i = 0; i < boxsaved; i++) {
sm(MyJSON[i]);
}
for (i = 0; i < MyJSON.length; i++) {
fnc(MyJSON[i]);
}
</script>
</body>
And .json file:
var MyJSON = [{
"url": 'google.es',
},
{
"url": 'yahoo.com',
}]
The problem is that your first box is the only element that your fnc function alters - notice that it only uses the hl1 id to access and alter an element, never hl2+.
I'll try to keep to your original approach, so that you'll follow it more easily. You might do something like this:
var cajas = 2;
function sm(info) {
cajas = cajas + 1;
document.getElementById("inf").innerHTML += (
'<div id="hl' + cajas + '">' + info.url + '</div>'
);
}
for (var i = 0; i < MyJSON.length; i++) {
sm(MyJSON[i]);
}
It is very difficult to read all the code, but as i've got it, you want to add some elements with url's from your JSON.
Ok, we have parent element div with id='inf', lets use javascript function appendChild to add new elements.
And we will use document.createElement('p') to create new elements.
Here is the code, as I've understood expected behavior.
var infContainer = document.getElementById('inf');
var elNumber = 2;
function agregar_caja() {
MyJSON.forEach(function(item,i) {
var newElement = document.createElement('p');
newElement.innerHTML = item.url;
newElement.id = 'hl'+elNumber;
elNumber++;
infContainer.appendChild(newElement);
}
)}

GoogleApp script. Google calendar script that display current day events

I have some questions regarding google calendar script that I'm building. So I managed to write the script and deploy it as a web app, but I encountered some problems:
1) It should list all current day events, but it lists only one event of the day
2) Also I want to display only the title of the event (it’s working now) and the start time and end time of the event. I managed to display a title (events[i].summary) and the start time of the event, but I was unable to display end time of the event and to change the format of the time that it would display time like this for example : 1pm – 2 pm.
3) Also what I want to do is to make the script run without pressing a button. I want it to work every time I open the published web app or refresh the web app page.
Here is the script code:
function doGet() {
return HtmlService.createHtmlOutputFromFile('calendarApp');
}
function listEvents() {
var actualDate = new Date();
var endOfDayDate = new
Date(actualDate.getFullYear(),actualDate.getMonth(),actualDate.getDate(),23,59,59);
var calendarId = 'primary';
var optionalArgs = {
timeMin: (new Date()).toISOString(),
timeMax: endOfDayDate.toISOString(),
showDeleted: false,
singleEvents: true,
maxResults: 10,
orderBy: 'startTime'
};
var response = Calendar.Events.list(calendarId, optionalArgs);
var events = response.items;
var allEvents = [];
if (events && events.length > 0) {
for (i = 0; i < events.length; i++) {
allEvents.push(events[i].summary + ' ' + events[i].start.dateTime);
}
return allEvents;
} else {
return ['No events found'];
}
And this is a HTML code:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<h1>Calendar App</h1>
<button onclick="listEvents()">List events</button>
<ul id='events'></ul>
<script>
function listEvents() {
google.script.run
.withSuccessHandler(function(response){
var events = response;
for(var i = 0; i < events.length; i++) {
document.getElementById('events').innerHTML = '<li>' + response[i] + '</li>';
}
})
.withFailureHandler(function(err){
console.log(err);
})
.listEvents();
};
</script>
</body>
</html>
This is the link to actual google scritp: Google Script
Thank you in advance for your help :)
Here is your modified (and working) code. You don't need to use advanced Calendar API since everything you need is available in CalendarApp, including a convenient getEventsForDay().
It shows all your events on opening as required.
code :
function doGet() {
return HtmlService.createHtmlOutputFromFile('calendarApp').setTitle('CalendarApp');
}
function listEvents() {
var today = new Date();
var cal = CalendarApp.getDefaultCalendar();
var events = cal.getEventsForDay(today);
var data = [];
data.push("Events for today "+Utilities.formatDate(today,Session.getScriptTimeZone(),"MMM dd yyyy"));
if (events && events.length > 0) {
for (i = 0; i < events.length; i++) {
data.push(events[i].getTitle()+' : '+Utilities.formatDate(events[i].getStartTime(),Session.getScriptTimeZone(),"HH:mm")+' - '+Utilities.formatDate(events[i].getEndTime(),Session.getScriptTimeZone(),"HH:mm"))
}
return data;
} else {
return ['No events found','',''];
}
}
html & script :
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body style="font-family:arial,sans;font-size:12pt">
<h2>Calendar App</h2>
<div id="events">
</div>
<script>
function listEvents() {
google.script.run
.withSuccessHandler(function(events){
document.getElementById('events').innerHTML = document.getElementById('events').innerHTML+'<p>' + events[0] + '</p>';
for(var i = 1; i < events.length; i++) {
document.getElementById('events').innerHTML = document.getElementById('events').innerHTML+'<li>' + events[i] + '</li>';
}
})
.withFailureHandler(function(err){
console.log(err);
})
.listEvents();
};
window.onload = listEvents();
</script>
</body>
</html>
Here's a function I use to get my calendar events for the next 5 weeks. And I use it in conjunction with a webapp so it gets returned to a statement that looks like this document.getElementById('hotbox').innerHTML=hl; hotbox is just a div.
function getMyEvents()
{
var allCals=CalendarApp.getAllCalendars();
var s=Utilities.formatString('<strong>%s</strong>',Utilities.formatDate(new Date(),Session.getScriptTimeZone(),"E MMM d, yyyy HHmm"))
var min=60 * 1000;
var hr=60 * min;
var day=24 * hr;
var wk=7 * day;
var start = new Date(new Date().setHours(0,0,0));
var end=new Date(start.valueOf() + (5 * wk));//you could make this + day instead of + (5 * wk)
var incl=['Calendar1Name','Calendar2Name'];//These are different calendar names as I have some special calendars for different functions
for(var i=0;i<allCals.length;i++)
{
if(incl.indexOf(allCals[i].getName())>-1)
{
s+=Utilities.formatString('<br /><strong>%s</strong>',allCals[i].getName());
var events=allCals[i].getEvents(start, end);
if(events)
{
s+='<br><ul>';
for(j=0;j<events.length;j++)
{
var calId=allCals[i].getId();
var evId=events[j].getId();
if(events[j].isAllDayEvent())
{
s+=Utilities.formatString('<li><strong>%s</strong>-%s %s <input type="checkbox" class="markdone" title="Delete Event" name="delevent" value="%s,%s" /></li>', events[j].getTitle(),'All Day',Utilities.formatDate(events[j].getStartTime(),Session.getScriptTimeZone(),"E MMM d"),calId,evId);
}
else
{
s+=Utilities.formatString('<li><strong>%s</strong>-%s <input type="checkbox" class="markdone" title="Delete Event" name="delevent" value="%s,%s" /></li>', events[j].getTitle(),Utilities.formatDate(events[j].getStartTime(),Session.getScriptTimeZone(),"E MMM d, HHmm"),calId,evId);
}
}
s+='</ul>';
}
}
}
s+='<br /><input type="button" value="Delete Selected Events" onClick="delSelectedEvents();" style="width:250px;height:35px;text-align:center;margin:10px 0 10px 0;" />';
//var ui=HtmlService.createHtmlOutput(s);
//SpreadsheetApp.getUi().showModelessDialog(ui, 'My Events');
return s;
}

Categories

Resources