How do I change a global variable from inside an EventListener function with JavaScript? - scope

I'm using getDay(); to display what's for lunch the day the visitor lands on my site.
However, I'd also like to let the user use a dropdown menu to see what's for lunch any day they'd like. I thought I could accomplish this with the function inside the EventListener at the bottom of the code but it's not working.
Some help would be deeply appreciated!
const daysOfWeek = ["---Välj dag---", "Måndag", "Tisdag", "Onsdag", "Torsdag", "Fredag", "Lördag", "Söndag"];
const h1 = document.createElement("h1");
h1.innerText ="Lunchrestaurangens meny";
document.body.appendChild(h1);
const p = document.createElement("p");
document.body.appendChild(p);
const p2 = document.createElement("p");
document.body.appendChild(p2);
const d = new Date();
let day = d.getDay();
switch (day) {
case 1:
p.innerText = "Dagens rätt måndag: Korvstroganoff";
break;
case 2:
p.innerText = "Dagens rätt tisdag: Raggmunkar med fläsk";
break;
case 3:
p.innerText = "Dagens rätt onsdag: Stekt strömming med skirat smör och potatismos";
break;
case 4:
p.innerText = "Dagens rätt torsdag: Ärtsoppa";
break;
case 5:
p.innerText = "Dagens rätt fredag: Tacos";
break;
case 6:
p.innerText = "På lördagar håller restaurangen stängt.";
break;
case 7:
p.innerText = "På söndagar håller restaurangen stängt.";
break;
}
p2.innerText = "Vill du se vad det blir för lunch en annan dag? Välj veckodag nedan!"
const chooseDay = document.createElement("select");
chooseDay.setAttribute("id", "chooseDay");
document.body.appendChild(chooseDay);
for (i = 0; i < daysOfWeek.length; i++) {
let days = document.createElement("option");
days.setAttribute("id", [i]);
document.getElementById("chooseDay").appendChild(days);
days.innerHTML = daysOfWeek[i];
}
chooseDay.addEventListener("change", () => {
let newDay = daysOfWeek.indexOf(chooseDay.value);
day = newDay;
});
I tried updating the day variable which would then be run by the switch statement with the following code:
chooseDay.addEventListener("change", () => {
let newDay = daysOfWeek.indexOf(chooseDay.value);
day = newDay;
But nothing happens.

Related

Discord.js Poll Command Cannot read property '0' of null

I'm trying to make a Discord.js poll command I keep getting this error Cannot read property '0' of null and help would be appreciated. I don't have any idea how to fix I've tried a lot of different ways around and they all didn't work :(
const { MessageEmbed } = require('discord.js')
module.exports = {
name : 'poll',
category : 'util',
cooldown: 5,
description : 'Makes a poll',
permissions: ["MANAGE_MESSAGES"],
run : async(client, message, args) => {
let num = {
1: '1️⃣',
2: '2️⃣',
3: '3️⃣',
4: '4️⃣',
5: '5️⃣',
6: '6️⃣',
7: '7️⃣',
8: '8️⃣',
9: '9️⃣',
10: '🔟'
}
var questionRe = /"(.*)"/gmi
let question = args.join(" ").match(questionRe)
if (!questionRe) return message.args("You did not provide question")
let options = args.join(" ").slice(question[0].length).split(" | ")
let result = ""
if (options.length <= 1) {
result += "✅ : Yes\n"
result += "❌ : No"
return message.send(`📊 ${question}`, `React with one of the following to determine your choice!\n${result}`, "BLUE").then(async msg => {
await msg.react("✅")
await msg.react("❌")
})
} else {
if (options.length > 9) return message.error("Cannot be more than 9 options")
result = options.map((c, i) => {
return `${num[i + 1]}: ${c}`
})
let msg = await message.sendE(`📊 ${question}`, `React with one of the following to determine your choice!\n${result.join('\n')}`, "BLUE")
options.map(async (c, x) => {
await msg.react(num[x + 1])
})
}
}
}
In this line the thing you should check is question instead of questionRe
if (!question || question.length === 0) return message.args("You did not provide question")

I have 7 drums display, each drum is supposed to make a different sound when you click on it

I'm taking this full-stack course, my code looks exactly as my instructor. Here's the problem, I have 7 drums display, each drum is supposed to make a different sound when you click on it, I'm using a switch statement to accomplish this, for some reason the switch statement is not working.
HTML
<h1 id="title">Drum 🥁 Kit</h1>
<div class="set">
<button class="w drum">w</button>
<button class="a drum">a</button>
<button class="s drum">s</button>
<button class="d drum">d</button>
<button class="j drum">j</button>
<button class="k drum">k</button>
<button class="l drum">l</button>
</div>
JavaScript
var numberOfButtons = document.querySelectorAll(".drum").length;
for (var i = 0; i < numberOfButtons; i++) {
document.querySelectorAll(".drum")[i].addEventListener("click", function() {
var buttonInnerHTML = this.innerHTML;
switch (buttonInnerHTML) {
case "w":
var tom1 = new Audio("sounds/tom-1.mp3");
tom1.play();
break;
case "a":
var kick - bass = new Audio("sounds/kick-bass.mp3");
kick - bass.play();
break;
case "s":
var snare = new Audio("sounds/snare.mp3");
snare.play();
break;
case "d":
var tom - 1 = new Audio('sounds/tom-1.mp3');
tom - 1. play();
break;
case "j":
var tom - 2 = new Audio("sounds/tom-2.mp3");
tom - 2. play();
break;
case "k":
var tom - 3 = new Audio("sounds/tom-3.mp3");
tom - 3. play();
break;
case "l":
var tom - 4 = new Audio("sounds/tom-4.mp3");
tom - 4. play();
break;
default:
console.log(buttontrig);
}
});
}
var names cannot contain "-". That was a bug in your code.
Another bug in your code was fixed by changing the var buttonInnerHTML to "buttonHTML".
Copy code:
var numberOfButtons = document.querySelectorAll(".drum").length;
for (var i = 0; i < numberOfButtons; i++) {
document.querySelectorAll(".drum")[i].addEventListener("click", function() {
var buttonHTML = this.innerHTML;
switch (buttonHTML) {
case "w":
var tom1 = new Audio("sounds/tom-1.mp3");
tom1.play();
break;
case "a":
var kick = new Audio("sounds/kick-bass.mp3");
kick.play();
break;
case "s":
var snare = new Audio("sounds/snare.mp3");
snare.play();
break;
case "d":
var tom1 = new Audio('sounds/tom-1.mp3');
tom1. play();
break;
case "j":
var tom2 = new Audio("sounds/tom-2.mp3");
tom2. play();
break;
case "k":
var tom3 = new Audio("sounds/tom-3.mp3");
tom3. play();
break;
case "l":
var tom4 = new Audio("sounds/tom-4.mp3");
tom4. play();
break;
default:
console.log(buttonHTML);
}
});
}

How to schedule the Job with job id and recurrence rule using node-schedule?

I'm using node-schedule npm package to schedule the job. I referred below link to set the job name/id for different jobs,
Cancel node-schedule event after it has been set
It works well when I directly use the cron expression to schedule the job. But it is not working when I used RecurrenceRule() to schedule the job.
Please help me to solve this problem.
Working code snippet for, scheduling job with job id and cron expression,
// code that works
function test(fn)
{
let rule = '* * * * *'
let jobId = "my_event_1"
schedule.scheduleJob(jobId,rule,()=>{fn()})
}
test(print)
print function,
function print()
{
console.log("HELLO",new Date())
}
Code that doesn't work with recurrence rule,
// Recurrence rule used
function my_scheduleJob(id,tz,cron_expression,function_name)
{
var mxTimezones = "Asia/Kolkata";
var interval = parser.parseExpression(cron_expression, options);
var cronDate = interval.next();
var rule = new schedule.RecurrenceRule();
rule.second = cronDate.getSeconds();
rule.minute = cronDate.getMinutes();
rule.tz = mxTimezones; // You can specify a timezone!
schedule.scheduleJob(rule,()=>{
console.log("Scheduler test-------")
function_name(rule.tz)
})
}
my_scheduleJob("job1", "Asia/Kolkata", "* * * * *", print)
The reason I used recurrence rule is to set the timezone. Is it possible to use recurrence rule and job id to schedule the job?
Thanks in advance !!!
I got the solution for this question after properly converting cron expression to recurrence rule. Hope the below code helps...
// Recurrence rule used
function my_scheduleJob(id, mxTimezones, cron_expression, function_name) {
var options = {
tz: mxTimezones
};
var interval = parser.parseExpression(cron_expression, options);
var cronDate = interval.next();
var cron_attr = cron_expression.split(' ');
var rule = new schedule.RecurrenceRule();
for (var i in cron_attr) {
var res = '';
switch (i) {
case '0':
res = getRuleValue(cron_attr[i], 0, 59);
rule.minute = res == '1' ? cronDate.getMinutes() : res;
break;
case '1':
res = getRuleValue(cron_attr[i], 0, 23);
rule.hour = res == '1' ? cronDate.getHours() : res;
break;
case '2':
res = getRuleValue(cron_attr[i], 1, 31);
rule.date = res == '1' ? cronDate.getDate() : res;
break;
case '3':
res = getRuleValue(cron_attr[i], 1, 12);
rule.month = res == '1' ? cronDate.getMonth() : res;
break;
case '4':
res = getRuleValue(cron_attr[i], 0, 6);
rule.dayOfWeek = res == '1' ? cronDate.getDay() : res;
break;
}
}
rule.tz = mxTimezones; // You can specify a timezone!
let jobId = String(id)
schedule.scheduleJob(jobId, rule, () => {
console.log("Scheduler test-------")
function_name();
})
}
my_scheduleJob("job1", "Asia/Kolkata", "* * * * *", print)
function getRuleValue(value, start_value, end_value) {
if (/^[*\d][\/][\d]+$/.test(value)) {
// console.log('value:', /^[\d][\/][\d]+$/.test(value));
return new schedule.Range(start_value, end_value, parseInt(value.split('/')[1]))
}
else if (value == 'MON-FRI') {
return new schedule.Range(1, 5);
}
else if (value == '*') {
return null;
}
else {
return '1';
}
}

Modifying variables from another file

i've got this in a file called voting_Request.js:
else
{
count1 = 0;
count2 = 0;
boolCheck = true;
module.exports.count1 = count1;
module.exports.count2 = count2;
}
and i've got this as well in a file called vote.js:
var request = require('./voting_Request.js');
async run(message,args){
var c1 = request.count1;
var c2 = request.count2;
if(!request.boolCheck){
message.reply('No ongoing votings please try again when a voting is available');
}
else{
if(request.voted.indexOf(message.author.tag) > -1){
message.reply("You have already voted!");
}
else{
request.noVote = false;
switch (args) {
case '1':
c1++;
message.reply('Thanks for voting!');
request.voted.push(message.author.tag);
break;
case '2':
c2++;
message.reply('Thanks for voting!');
request.voted.push(message.author.tag);
break;
default:
message.reply(args + ' is not an available option');
}
module.exports.c1 = c1;
module.exports.c2 = c2;
}
}
}
and basicallyinstead of taking the VALUE of count1 and count2 from the request file and only copying it into new variables in vote.js, i want to modify them from vote.js but the value in count1 and count2 will change depending on vote.js.
Thanks for the help!

C# Object reference not set to an instance

what does it mean Object reference not set to an instance of an object in the line below?
case "S Connected":
List dd6 = new List(textBox1.Text);
**dd6.textBox2.Text = id.ToString();**
dd6.ShowDialog();
Thanks, guys. The first case works perfectly, the W connected and the S connected retrieve the error:
private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
var id = dataGridView1.CurrentRow.Cells["Id"].Value;
var BBB = dataGridView1.CurrentRow.Cells["Connected"].Value;
string idd = id.ToString();
string BBB2 = BBB.ToString();
textBox1.Text = id.ToString();
switch (BBB2)
{
case "Standalone":
ListStandalone dd = new ListStandalone(textBox1.Text);
dd.textBox2.Text = id.ToString();
dd.ShowDialog();
break;
case "W Connected":
ListW da2 = new ListW(textBox1.Text);
da2.textBox2.Text = id.ToString();
da2.ShowDialog();
break;
case "S Connected":
ListS dd6 = new ListS(textBox1.Text);
dd6.textBox2.Text = id.ToString();
dd6.ShowDialog();
break;
case "Retail":
PrintRetail dd4 = new PrintRetail(textBox1.Text);
dd4.Show();
break;
}

Resources