I'm creating a todo list in javascript and I'm in the adding phase
tasks for the user. He wants to do so that if the user enters a task, he cannot enter it again
const taskInput = document.getElementById('enter-task');
const addTaskBtn = document.querySelector('[data-submit-task]');
const toDoContainer = document.querySelector('[data-todo]');
addTaskBtn.addEventListener('click', addTask);
function addTask() {
if (taskInput.value == '') {
alert("Pole nie może być puste");
return;
}
const taskContainer = document.createElement('div');
taskContainer.classList.add('task-container');
taskContainer.innerHTML = `<input type="checkbox" data-complete><p class="task-date">Data utworzenia: <span data-task-date>${getDate()}</span></p><div class="content-edit"><span data-task-title>${taskInput.value}</span><button type="button" data-edit>Edycja</button></div><button type="button" data-delete>X</button>`;
const completeTaskBtn = taskContainer.querySelector('[data-complete]');
const deleteTaskBtn = taskContainer.querySelector('[data-delete]');
const editTaskBtn = taskContainer.querySelector('[data-edit]');
completeTaskBtn.addEventListener('click', markAsDone);
deleteTaskBtn.addEventListener('click', deleteTask);
editTaskBtn.addEventListener('click', editTask);
toDoContainer.appendChild(taskContainer);
}
function markAsDone() {
const taskTitle = this.parentNode.querySelector('[data-task-title]');
if (this.checked) {
taskTitle.style.textDecoration = 'line-through';
return;
}
taskTitle.style.textDecoration = 'none';
}
function deleteTask() {
toDoContainer.removeChild(this.parentNode);
}
function editTask() {
const taskContainer = this.parentNode.parentNode;
if (taskContainer.contains(taskContainer.querySelector('.task-edit-container'))) {
alert("Nie możesz dodać więcej niż jednego pola do edycji");
return;
}
const currentTaskTitle = this.previousElementSibling;
const editTaskContainer = document.createElement('div');
editTaskContainer.classList.add('task-edit-container');
editTaskContainer.innerHTML = `<label>Wprowadź treść zadania</label><input type="text"><button type="button">OK</button>`;
const submitTitleBtn = editTaskContainer.querySelector('button');
submitTitleBtn.addEventListener('click', function() {
const newTitle = editTaskContainer.querySelector('input').value;
if(newTitle == '') {
alert("Pole do edycji nie może być puste");
return;
}
const currentDate = document.querySelector('[data-task-date]');
currentDate.innerHTML = `${getDate()}`;
currentTaskTitle.innerHTML = newTitle;
taskContainer.removeChild(editTaskContainer);
});
taskContainer.appendChild(editTaskContainer);
}
function getDate() {
let date = new Date();
let day = date.getDate();
let monthIndex = date.getMonth();
let year = date.getFullYear();
let hours = date.getHours();
let minutes = date.getMinutes();
let seconds = date.getSeconds();
if(minutes < 10) minutes = "0" + minutes;
if(seconds < 10) seconds = "0" + seconds;
const months = ["Styczeń", "Luty", "Marzec", "Kwiecień", "Maj", "Czerwiec", "Lipiec", "Sierpień", "Wrzesień", "Październik", "Listopad", "Grudzień"];
return `${day} ${months[monthIndex]} ${year} ${hours} : ${minutes} : ${seconds}`;
}
Here is the code responsible for adding editing as well as removing tasks from the todo list and generating the date when adding a task as well as editing it. Now he wants to do so that if the user creates a task for himself, he will normally be added to the list, while if he wants to add the same task to the list of tasks again, he will return a message like "You have already added this task"
What you can do is create array or something where you store all the added tasks and when you add new task just check whether same task is available inside array or not, if it is available you can show some message to user saying already available.
Related
I am writing my first Discord bot and I am fairly new to JavaScript, especially dealing with libraries such as Discord.JS. My project here is a Reminder Discord bot, which takes a user input by prefix, stores and checks data based on time, then outputs a user inputted message when the user time set is the same as current time (to alert).
My current issue is that I don't know how to send a message to a discord channel using the client outside of the two specificed scopes. Ideally, I'd like to send a message between
if (userTime === machineTime) {
console.log("Reminder!");
clearInterval();
}
Thank you
const { Client, GatewayIntentBits, EmbedBuilder, PermissionsBitField, Permissions } = require(`discord.js`);
const { type } = require("os");
const prefix = '!';
const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent] });
var machineTime = null;
var userTime = null;
// Discord Client Ready Check
client.on("ready", () => {
console.log("Bot is online!")
})
// Message Listener
client.on("messageCreate", (message) => {
if (message.author.bot) return;
//Split input into array & get current date
var content = message.content.split(" ");
console.log(content);
// Output
if (content[0] === prefix + 'set-reminder'){
//Start timer
setInterval(checkTime, 1000);
//Convert user time
var inputTime = content[2].split(':');
var inputDate = content[1].split('/');
//Change store metrics and format date
var convertMinutes = parseInt(inputTime[1]);
var convertHours = parseInt(inputTime[0]);
var convertMonth = parseInt(inputDate[0]);
var convertDay = parseInt(inputDate[1]);
var formatDate = convertMonth + "/" + convertDay + "/" + inputDate[2];
//If PM add 12 hours to time input
if (content[3].toLowerCase() === "pm") {
convertHours += 12;
}
userTime = formatDate + " " + convertHours + " " + convertMinutes;
//Send reminder confirmation
message.channel.send("Members will be alerted at " + content[1] + ":white_check_mark:");
}
// Input Array: 0 = prefix, 1 = date, 2 = time, 3 = am/pm, 4 = channel, 5 = message
})
//Current Time Check
const checkTime = () => {
var machineOutput = new Date();
var machineDate = machineOutput.toLocaleDateString();
var machineMinutes = machineOutput.getMinutes();
var machineHours = machineOutput.getHours();
machineTime = machineDate + " " + machineHours + " " + machineMinutes;
if (userTime === machineTime) {
console.log("Reminder!");
clearInterval();
}
console.log(machineTime);
}
client.login("MY_LOGIN_KEY");```
As long as you have access to the client, you can send a message to any channel.
if (userTime === machineTime) {
console.log("Reminder!");
clearInterval();
const channel = await client.channels.fetch('channel id');
channel.send('...');
}
I have been working on a personal project of user check In/Out time recorder. I created the multi user login and time recorder using JS. I faced an issue to record the time of each logged in user. The code I created is only able to record the time of single user. I used localStorage command to store time because it need to be displayed every users time data on admin page. I am using single JS file for login, user page recorder and also for admin page loader. Plz help me out if anyone has any solution. I can't use server based code right now. I only have to write this web-app code in html,css and javascript.
var users= [
{user : 'user1', pass: 'pass1'},
{user : 'user2', pass: 'pass2'},
{user : 'user3', pass: 'pass3'},
{user : 'admin', pass: 'admin'}
];
function login()
{
//login page
var username = document.getElementById('uname').value;
var password = document.getElementById('psw').value;
for (var i = 0; i < users.length; i++)
{
console.log('enter the loop');
console.log("current user: ", i+1);
if (username == users[i].user && password == users[i].pass)
{
window.location.href = 'user.html';
alert("Login Successful");
break;
}
else if (i == (users.length-1))
{
alert('Login failed! Try Again');
console.log(i,'-times wrong');
}
else if (username == users[3].user && password == users[3].pass)
{
console.log('admin login');
window.location.href = 'admin.html';
break;
}
else
{
console.log('else statement');
}
}
var userId = i;
console.log("current user: ", userId);
}
//Date & Time Display
setInterval(myTimer,1000);
function myTimer()
{
const d = new Date();
document.getElementById('date').innerHTML = d.toLocaleDateString();
document.getElementById('time').innerHTML = d.toLocaleTimeString();
}
let date = document.getElementById('date');
let time = document.getElementById('time');
let newDate = new Date();
let year = newDate.getFullYear();
let month = newDate.getMonth();
let todaysDate = newDate.getDate();
let hours = newDate.getHours();
let minutes = newDate.getMinutes();
let seconds = newDate.getSeconds();
var cal = {
data : null,
sMth : 0,
sYear : 0,
init : () => {
let newDate = new Date();
cal.sDay = newDate.getDate();
cal.sMth = newDate.getMonth();
cal.hour = newDate.getHours();
cal.minutes = newDate.getMinutes();
cal.date = document.getElementById('date');
cal.data = localStorage.getItem("cal-" + cal.sDay + "-" + cal.sMth);
if (cal.data == null)
{
localStorage.setItem("cal-" + cal.sDay + "-" + cal.sMth, "{}");
cal.data = {};
console.log("cal.data: null-",cal.data);
}
else
{
cal.data = JSON.parse(cal.data);
console.log("cal.data: JSON-",cal.data);
}
},
checkIn : () => {
cal.data[cal.sDay] = cal.hour + ":" + cal.minutes;
localStorage.setItem('cal-${cal.sDay}-${cal.sMth}',JSON.stringify(cal.data));
console.log('Time:', cal.data);
}
}
window.onload = cal.init;
I am trying to implement a function that checks if the date and time I choose have already been chosen before, if so, it gives an error, if not it lets me carry on with adding the ticket. The current function does save options to local storage, however it looks like it doesn't retrieve them for me and allows me to choose the same date twice.
var count = 0;
function store() {
let clickCounter = localStorage.getItem("clickCount");
if (!clickCounter) {
localStorage.setItem("clickCount", 0);
clickCounter = "0";
}
clickCounter = parseInt(clickCounter);
document.getElementById('inc').value = ++count;
if (clickCounter == 100) {
console.log("Limit reached");
return;
} else {
localStorage.setItem("clickCount", clickCounter + 1);
}
console.log("Saving");
var e = document.getElementById("time");
var time = e.options[e.selectedIndex].text;
var date = document.querySelector("input").value;
localStorage.setItem(JSON.stringify(time), date);
console.log(localStorage);
if (!localStorage.getItem("history")) {
localStorage.setItem("history", "[]");
}
const history = JSON.parse(localStorage.getItem("history"));
history.push({ [JSON.stringify(time)]: date });
localStorage.setItem("history", JSON.stringify(history));
console.log(localStorage.getItem("history"));
}
function myDate(date) {
var today = new Date();
var newDate = new Date(date);
var nextWeek = new Date();
var pastWeek = new Date();
nextWeek.setDate(nextWeek.getDate() + 7);
pastWeek.setDate(pastWeek.getDate() - 7);
const dateInput = document.getElementById('date');
if (newDate < pastWeek || newDate > nextWeek) {
document.getElementById("time").disabled = true;
console.log("error")
return;
} else {
document.getElementById("time").disabled = false;
}
}
I am trying to show the hourly weather on my website from this API: https://opendata-download-metfcst.smhi.se/api/category/pmp3g/version/2/geotype/point/lon/18.1489/lat/57.3081/data.json
I have a hard time understanding the functions needed to do so. I think I need some sort of loop, but can't figure out what to put in it. This is my code so far:
export async function getWeather() {
var res = await fetch("https://opendata-download-metfcst.smhi.se/api/category/pmp3g/version/2/geotype/point/lon/18.1489/lat/57.3081/data.json");
if (res.ok)
return await res.json();
else
alert('HTTP Error: ' + res.status);
}
--My other file--
import {getWeather} from './fetch.js'
async function generate_weather() {
var jsonRes = await getWeather();
var i = 0;
if(jsonRes.timeSeries[i].validTime == timeNow())
{
document.createTextNode(jsonRes.timeSeries[i].parameters[i].values[0] + " grader");
}
}
function timeNow() {
var date = new Date();
var hours = date.getHours();
return hours;
}
generate_weather();
I tried the example below, but it didn't work. Am I missing a step?
async function generate_weather() {
var jsonRes = await getWeather();
for (let times in jsonRes.timeSeries) {
let currentTime = times.validTime;
let date = new Date(currentTime);
let currentHour = date.getHours();
for (let param in times.parameters) {
let value = param.values[0];
let unit = param.unit;
}
for (var i = 0; i == currentHour;) {
var newElement = document.createElement('h2');
var newElementText = document.createTextNode(jsonRes.timeSeries[i].times[i].parameters[0]);
newElement.appendChild(newElementText);
document.getElementById("body").appendChild(newElement);
}
}
}
generate_weather();
In response, you have two arrays one for timeseries and other for parameters inside the timeseries-
So, you will have to use loop inside the loop like this in generate_weather function -
for (let times in jsonRes.timeSeries) {
let currentTime = times.validTime;
let date = new Date(currentTime);
let currentHour = date.getHours();
for (let param in times.parameters) {
let name = param.name;
let value = param.values[0];
let unit = param.unit;
Console.log('Tempreture of ' + name + ' is ' + value + ' ' + unit); // Tempreture of t is 14.8 Cel
}
}
Above code will show the tempreture of every name per every hour, if you need to show the tempreture for any specific name then you can use if/else statement.
There is a variable which contains event time. I want to redirect user if event time + 04:38 is more than current time.
Below is the code i have tried:
var deadline = getDayInstance("Monday","08:00:59")
function getDayInstance(day,time) {
const days = {"Sunday":0,"Monday":1,"Tuesday":2,"Wednesday":3,"Thursday":4,"Friday":5,"Saturday":6};
if(days[day]!==undefined)
var dayINeed = days[day];
else
var dayINeed = 2; // for Tuesday
const today = moment().tz("America/Los_Angeles").isoWeekday();
var dt;
// if we haven't yet passed the day of the week that I need:
if (today <= dayINeed) {
dt = moment().tz("America/Los_Angeles").isoWeekday(dayINeed).format('YYYY-MM-DD')+"T"+time;
}
else {
dt = moment().tz("America/Los_Angeles").add(1, 'weeks').isoWeekday(dayINeed).format('YYYY-MM-DD')+"T"+time;
}
console.log("Event Time: "+dt);
var maxLimit = Date.parse(moment(time,'HH:mm:ss').tz("America/Los_Angeles").add({"hours":4,"minutes":43,"seconds":33}).format("YYYY-MM-DDTHH:mm:ss"));
var now = Date.parse(moment().tz("America/Los_Angeles").format('YYYY-MM-DDTHH:mm:ss'));
if(maxLimit < now)
{
dt = moment().tz("America/Los_Angeles").add(1, 'weeks').isoWeekday(dayINeed).format('YYYY-MM-DD')+"T"+time;
window.setVideo = false;
}
console.log(moment(time,'HH:mm:ss').tz("America/Los_Angeles").add({"hours":4,"minutes":43,"seconds":33}).format("YYYY-MM-DDTHH:mm:ss"));
console.log(moment().tz("America/Los_Angeles").format('YYYY-MM-DDTHH:mm:ss'));
return dt;
}
var maxLimit = Date.parse(moment(deadline,'YYYY-MM-DDTHH:mm:ss').add({"hours":4,"minutes":43,"seconds":33}).format("YYYY-MM-DDTHH:mm:ss"));
var now = Date.parse(moment().tz("America/Los_Angeles").format('YYYY-MM-DDTHH:mm:ss'));
if(maxLimit>=now){
var redirectTo = $("#lp-pom-button-673").attr('href');
if(redirectTo.length > 3){
window.location.href = redirectTo;
}
else{
window.location.href = "https://******/";
}
}
I need to maintain timezone in calculation.
I got the answer of this after refining the process theoretically and then try to implement it in JS. Below is the new code that can be used for this.
var deadline = getDayInstance("Tuesday", "02:32:00");
var maxLimit,now;
function getDayInstance(day,time) {
const days = {"Sunday":0,"Monday":1,"Tuesday":2,"Wednesday":3,"Thursday":4,
"Friday":5,"Saturday":6};
if(days[day]!==undefined)
var dayINeed = days[day];
else
var dayINeed = 2; // for Tuesday
const today = moment().tz("America/Los_Angeles").isoWeekday();
var dt;
// if we haven't yet passed the day of the week that I need:
if (today <= dayINeed) {
dt = moment().tz("America/Los_Angeles").isoWeekday(dayINeed)
.format('YYYY-MM-DD')+"T"+time;
}
else {
dt = moment().tz("America/Los_Angeles").add(1, 'weeks')
.isoWeekday(dayINeed).format('YYYY-MM-DD')+"T"+time;
}
var d = new Date(dt);
d.setHours(d.getHours() + 4);
d.setMinutes(d.getMinutes() + 43);
d.setSeconds(d.getSeconds() + 32);
max = Date.parse(d);
now = Date.parse(moment().tz("America/Los_Angeles").format('YYYY-MM-DDTHH:mm:ss'));
if(maxLimit < now)
{
dt = moment().tz("America/Los_Angeles").add(1, 'weeks')
.isoWeekday(dayINeed).format('YYYY-MM-DD')+"T"+time;
}
return dt;
}
if(maxLimit>=now){
var redirectTo = $("#lp-pom-button-673").attr('href');
if(redirectTo.length > 3){
window.location.href = redirectTo;
}
else{
window.location.href = "https://******/";
}
}