I have a simple form for readers to add comments. The comments entered are listed on the website when added. I would like to register the date the comment was entered and list that underneath the comment itself, as shown on the website. Can someone assist me with the JS code for this?
Thanks, Paul
const field = document.querySelector('textarea');
const comments = document.getElementById('comment-box');
// array to store the comments
var comments_arr = [];
if(!localStorage.commentData){localStorage.commentData = [];}
else{
comments_arr = JSON.parse(localStorage.commentData);
}
// to generate html list based on comments array
const display_comments = () => {
let list = '<ul>';
comments_arr.forEach(comment => {
list += `<li>${comment}</li>`;
})
list += '</ul>';
comments.innerHTML = list;
}
submit.onclick = function(event){
event.preventDefault();
const content = field.value;
if(content.length > 0){ // if there is content
// add the comment to the array
comments_arr.unshift(content);
localStorage.commentData = JSON.stringify(comments_arr);
// re-genrate the comment html list
display_comments();
// reset the textArea content
field.value = '';
}
}
window.addEventListener('load', display_comments);
<link href="comment.css" rel="stylesheet">
<form>
<textarea id="comment" placeholder="Your response pls." value=""></textarea>
</form>
<input id="submit" type="submit" value="add">
<h4>Responses</h4>
<div id="comment-box"></div>
<script src="comment.js"></script>
if you only want date stamp then remove the var current_time from the display_comments() function.
const display_comments = () => {
var date = new Date();
var current_date = date.getFullYear()+"-"+(date.getMonth()+1)+"-"+ date.getDate();
var current_time = date.getHours()+":"+date.getMinutes()+":"+ date.getSeconds();
var date_time = current_date+" "+current_time;
let list = '<ul>';
comments_arr.forEach(comment => {
list += `<li>${comment} created at : ${date_time}</li>`;
})
list += '</ul>';
comments.innerHTML = list;
}
let textbox=document.getElementById("textbox")
let comments=document.getElementById("comments")
let add=()=>{
let value=textbox.value
let ul=document.getElementById("ul")
let list=document.createElement("li")
var date = new Date();
var current_date = date.getFullYear()+"-"+(date.getMonth()+1)+"-"+ date.getDate();
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12;
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
var date_time = current_date+" "+strTime;
list.innerHTML=`comment:${value}`+" "+`Created At:${date_time}`
ul.insertBefore(list,ul.firstElementChild)
textbox.value=""
}
<textarea id="textbox" placeholder="Your response pls." value=""></textarea>
<button id="btn" onclick="add()">Add</button>
<div id="comments">
<h4>Responses</h4>
<ul id="ul"></ul>
</div>
Related
every day add the value in the div with + 1 a type of counter
...
var i = 1;
$(".teste").each(function () {
i = parseFloat(i) + parseFloat($(this).data("teste"));
});
$(".teste").html(i);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="teste" data-teste="2" id="teste"> </div>
If you want to increment i by 1 every day you will need some kind of loop and check against the date to see if the day has changed.
var i = parseInt($(this).data("teste")) + 1;
var running = true;
var currentDate = new Date();
while (running == true)
{
if (currentDate.toDateString() != (new Date()).toDateString())
{
i = parseInt(i) + parseInt($(this).data("teste"));
$(".teste").html(i);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="teste" data-teste="2" id="teste"> </div>
I have my DOM like this :
<input type="number" id="input" value="" placeholder="Enter time in minutes">
<button id="button">Go</button>
<button id="reset">reset</button>
<div class="timer">
<div class="mint" id="mint"></div>
<div class="sec" id="sec"></div>
</div>
And my JavaScript Like this :
let currentTime = 0;
let intervalClear;
let input = document.getElementById('input');
let button = document.getElementById('button')
button.addEventListener('click', ()=>{
let value = input.value * 60000;
function getTime(){
currentTime++
function backcount(currentTime){
let output = value - currentTime
console.log(output);
const mint = document.getElementById('mint'),
sec = document.getElementById('sec');
let minute = Math.floor(output/60000)
let second = ((output % 60000) / 1000).toFixed(0)
mint.innerText = minute;
sec.innerText = second;
if(output == 0){
clearInterval(intervalClear)
}
}
backcount(currentTime);
}
getTime()
intervalClear = setInterval(getTime, 1000)
})
const reset = document.getElementById('reset')
reset.addEventListener('click', ()=>{
clearInterval(intervalClear);
input.value = '';
})
now I want to display value in my web page But it doesn't updating. seems like its freezes. but my "setInterval()" running properly.
How can I resolve this issue? need help!
You need instead of this code
let output = value - currentTime
use this
let output = value - (currentTime * 1000)
let currentTime = 0;
let intervalClear;
let input = document.getElementById('input');
let button = document.getElementById('button')
button.addEventListener('click', ()=>{
let value = input.value * 60000;
function getTime(){
currentTime++
function backcount(currentTime){
let output = value - (currentTime * 1000)
console.log(output);
const mint = document.getElementById('mint'),
sec = document.getElementById('sec');
let minute = Math.floor(output/60000)
let second = ((output % 60000) / 1000).toFixed(0)
mint.innerText = minute;
sec.innerText = second;
if(output == 0){
clearInterval(intervalClear)
}
}
backcount(currentTime);
}
getTime()
intervalClear = setInterval(getTime, 1000)
})
const reset = document.getElementById('reset')
reset.addEventListener('click', ()=>{
clearInterval(intervalClear);
input.value = '';
})
<input type="number" id="input" value="" placeholder="Enter time in minutes">
<button id="button">Go</button>
<button id="reset">reset</button>
<div class="timer">
<div class="mint" id="mint"></div>
<div class="sec" id="sec"></div>
</div>
Based on #Oleg Barabanov's answer I found one bug. If you didn't enter any value in text box or first added value then click on "Reset" and click on "Go" button then counter started with negative value. I fixed that issue with this code.
Script
var intervalClear;
var input = document.querySelector('#input');
var mint = document.querySelector('#mint');
var sec = document.querySelector('#sec');
var go_button = document.querySelector('#button');
var reset_button = document.querySelector('#reset');
go_button?.addEventListener('click', () => {
if (input.value != '' && input.value != 0 && parseInt(input.value) != NaN) {
startTimer(input.value, mint, sec);
}
});
reset_button?.addEventListener('click', () => {
clearInterval(intervalClear);
mint.textContent = '00';
sec.textContent = '00';
});
function startTimer(duration, minElement, secElement) {
clearInterval(intervalClear);
var timer = duration * 60, minutes, seconds;
intervalClear = setInterval(function () {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
minElement.textContent = minutes;
secElement.textContent = seconds;
if (--timer < 0) {
timer = duration;
}
if (minutes == 0 && seconds == 0) {
clearInterval(intervalClear);
mint.textContent = '00';
sec.textContent = '00';
}
}, 1000);
}
DOM
<input type="number" id="input" placeholder="Enter time in minutes" >
<button id="button">Go</button>
<button id="reset">reset</button>
<div class="timer">
<div class="mint" id="mint">00</div>
<div class="sec" id="sec">00</div>
</div>
I am in need of having a3 checkboxes that should have a tick mark from 2 pm till 11 pm IST in javascript or HTML. This is what I tried
<html>
<body>
<center>
<span style="margin-left:50px; margin-top:0px;">
<p align="left"><font color="white"> <b> India Time: 2pm to 11pm IST </b>
</br>
<input type="checkbox" id="user1" name="user1" value="user1" > User1<br>
<input type="checkbox" id="user2" name="user2" value="user2" > User2<br>
<input type="checkbox" id="user3" name="user3" value="user3" > User3<br>
</p>
<img border="1" src="https://i.postimg.cc/VkPzvHCJ/gh.png" style=" margin-top:-129px;" >
</span>
<h3 style= "font-family: "Gotham A","Gotham B",sans-serif;>
<br> <p align="center" style=" margin-top:-30px;"> <font color="#339933"> <b>RStudio Dashboard
</h3></P>
</body>
<script>
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10){dd='0'+dd}
if(mm<10){mm='0'+mm}
var today = dd+'/'+mm+'/'+yyyy;
var holidays = [];
holidays = ["01/01/2019" , "26/01/2019" , "20/02/2019" , "01/05/2019" , "27/05/2019" , "04/06/2019", "04/07/2019" , "15/08/2019" , "02/09/2019" , "10/09/2019" , "02/10/2019" , "28/11/2019" , "25/12/2019"];
//var n = str.indexOf("welcome");
if {
var startTime = '2:00 PM';
var endTime = '11:00 PM';
var curr_time = getval();
//var curr_time = '12:39 AM';
//alert(curr_time);
if (get24Hr(curr_time) > get24Hr(startTime) && get24Hr(curr_time) < get24Hr(endTime)) {
//in between these two times
//alert("Yes")
document.getElementById("sid").checked = true;
document.getElementById("anil").checked = true;
document.getElementById("vin").checked = true;
} else {
//document.getElementById("user1").checked = true;
//document.getElementById("user2").checked = true;
}
function get24Hr(time){
var hours = Number(time.match(/^(\d+)/)[1]);
var AMPM = time.match(/\s(.*)$/)[1];
if(AMPM == "PM" && hours<12) hours = hours+12;
if(AMPM == "AM" && hours==12) hours = hours-12;
var minutes = Number(time.match(/:(\d+)/)[1]);
hours = hours*100+minutes;
console.log(time +" - "+hours);
return hours;
}
function getval() {
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
if (minutes < 10) minutes = "0" + minutes;
var suffix = "AM";
if (hours >= 12) {
suffix = "PM";
hours = hours - 12;
}
if (hours == 0) {
hours = 12;
}
var current_time = hours + ":" + minutes + " " + suffix;
return current_time;
}
}
else
{
print ("hello")
}
</script>
</html>
This is what I tried. The code is working, but it seems a bit complicated. Is there any simple method?
The only requirement is to tick the checkboxes from 2 pm to 11 pm IST
Add this js function. And then add "onClick" on every Input. Also the name must be the same.
<script language="JavaScript">
function toggle(source) {
checkboxes = document.getElementsByName('user');
for(var i=0, n=checkboxes.length;i<n;i++) {
checkboxes[i].checked = source.checked;
}
}
</script>
<input type="checkbox" onClick="toggle(this)" id="user1" name="user" value="user1" > User1<br>
<input type="checkbox" onClick="toggle(this)" id="user2" name="user" value="user2" > User2<br>
<input type="checkbox" onClick="toggle(this)" id="user3" name="user" value="user3" > User3<br>
I'm trying to make an alert to user when choose a date. For example, when user choose 2018-09-13, then the alert will show message "7 days later will be 2018-09-20". But instead, the alert message shows 2018-09-137.
<input type="date" name = "date" id = "date" onchange="javascript:var chooseDate=(this.value)+7; alert('7 days later will be '+chooseDate);" >
How should I add days into the date ?? please help, thank you.
this.value will return the date as string using the format YYYY-MM-DD, so if you "add" 7, it will be YYYY-MM-DD7. What you could do is create a new Date object, and then add the days you want, like this:
var chooseDate=new Date(this.value);
chooseDate.setDate(chooseDate.getDate()+7);
alert('7 days later will be '+chooseDate);
This will give you the complete date, though, which is something you probably don't want, so you would have to get the values you actually need, like this:
var chooseDate=new Date(this.value);
chooseDate.setDate(chooseDate.getUTCDate()+7);
var futureDate = chooseDate.getFullYear()+'-'+('0'+(chooseDate.getMonth()+1)).slice(-2)+'-'+('0'+(chooseDate.getDate())).slice(-2);
alert('7 days later will be '+chooseDate);
Here you have a working example:
<input type="date" name = "date" id = "date" onchange="var chooseDate=new Date(this.value);chooseDate.setDate(chooseDate.getUTCDate()+7);var futureDate=chooseDate.getFullYear()+'-'+('0'+(chooseDate.getMonth()+1)).slice(-2)+'-'+('0'+(chooseDate.getDate())).slice(-2);alert('7 days later will be '+futureDate);" >
How about this in :
addDays = function(input_date, days) {
var date = new Date(input_date);
date.setDate(date.getDate() + days);
return date;
}
You then call do addDays(this.value, 7) in onchange().
And, please reference on getDate() and setDate().
You are working with string instead of a date object:
function lPad(val) {
return ((10 > val ? '0' : '') + val);
}
function add(input, unit, value) {
var cur = input.value;
var byValue = Number(value);
if (!/^\d{4}\-\d{2}\-\d{2}$/.test(cur) || !/day|month|year/.test(unit) || isNaN(byValue)) {
console.warn('invalid parameters!');
return false;
}
var dt = new Date(cur.replace(/\-/g, '/'));
if (!dt || isNaN(dt)) {
console.warn('invalid date!');
return false;
}
if ('day' === unit) {
dt.setDate(dt.getDate() + byValue);
} else if ('month' === unit) {
dt.setMonth(dt.getMonth() + byValue);
} else {
dt.setFullYear(dt.getFullYear() + byValue);
}
input.value = [dt.getFullYear(), lPad(1 + dt.getMonth()), lPad(dt.getDate())].join('-');
console.log(cur, value, unit, '=', input.value);
return true;
}
<input type="date" onchange="add(this,'day','+7');" title="+7 days" />
<input type="date" onchange="add(this,'month','-1');" title="-1 month" />
<input type="date" onchange="add(this,'year','+2');" title="+2 year" />
try this one ...
<input type="date" name = "date" id = "date" onchange="ggrr(this)" >
<script>
function ggrr(input){
var dateString = input.value;
var myDate = new Date(dateString);
var d = new Date(Date.parse(myDate));
var y = d.getFullYear();
var da = d.getDate() + 7;
var m = d.getMonth();
console.log(y+':'+m+':'+da);
}
</script>
I'm making a calendar app where I'm trying to validate if the date entered is during the current semester, and then see if it is a holiday that we don't have class. I have an index of all of the dates that we are out with the names of the respective holidays, but when I tried to use indexOf, the code broke.
this is the html:
<form onsubmit="holiday()" method="post">
<fieldset>
Enter Date: <input type='date' id="dat"><p>
<input class="ubmit" type=submit >
</fieldset>
</form>
<p id="output"></p>
this is the js:
var dvalue = document.getElementById("dat").value;
function holiday(){
var txt ="boo";
dvalue=Date.parse(dvalue);
console.log(dvalue);
if (dvalue<1473033600000 || dvalue>1494979200000 || dvalue=="NaN"){
txt="This is not a valid date for this calendar app";
}
else function validate(dvalue){
var holidayz=new Array();
holidayz[0]=["Columbus Day",1473033600000];
holidayz[1]=["Fall Recess",1476057600000];
holidayz[2]=["Thanksgiving Recess",1479859200000];
holidayz[3]=["Thanksgiving Recess",1479945600000];
holidayz[4]=["Thanksgiving Recess",1480032000000];
holidayz[5]=["Thanksgiving Recess",1480118400000];
holidayz[6]=["President's Day",1487548800000];
holidayz[7]=["Spring Recess",1489363200000];
holidayz[8]=["Spring Recess",1489449600000];
holidayz[9]=["Spring Recess",1458000000000];
holidayz[10]=["Spring Recess",1489622400000];
holidayz[11]=["Spring Recess",1489708800000];
holidayz[12]=["Reading Day",1494288000000];
holidayz[13]=["Memorial Day",1496016000000];
holidayz[14]=["Independence Day",1499126400000];
if (holidayz.includes(dvalue)){
var mydate = new Date(dvalue);
console.log("<p>" + mydate + "<p>");
var day = mydate.getUTCDate();
var month = mydate.getMonth()+1;
var year = mydate.getFullYear();
console.log (month + "/" + day +"/" + year);
var holival= asList(holidayz).indexOf(dvalue);
console.log(holival)
}
}
console.log(txt)
document.getElementById("output").innerHTML = txt;
}
Try this,
var dvalue = document.getElementById("dat").value;
function holiday(){
var txt ="boo";
dvalue=Date.parse(dvalue);
console.log(dvalue);
if (dvalue<1473033600000 || dvalue>1494979200000 || dvalue=="NaN"){
txt="This is not a valid date for this calendar app";
} else {
var holidayz=new Array();
holidayz[0]=["Columbus Day",1473033600000];
holidayz[1]=["Fall Recess",1476057600000];
holidayz[2]=["Thanksgiving Recess",1479859200000];
holidayz[3]=["Thanksgiving Recess",1479945600000];
holidayz[4]=["Thanksgiving Recess",1480032000000];
holidayz[5]=["Thanksgiving Recess",1480118400000];
holidayz[6]=["President's Day",1487548800000];
holidayz[7]=["Spring Recess",1489363200000];
holidayz[8]=["Spring Recess",1489449600000];
holidayz[9]=["Spring Recess",1458000000000];
holidayz[10]=["Spring Recess",1489622400000];
holidayz[11]=["Spring Recess",1489708800000];
holidayz[12]=["Reading Day",1494288000000];
holidayz[13]=["Memorial Day",1496016000000];
holidayz[14]=["Independence Day",1499126400000];
holidayz[15]=["Test Day",1476921600000];
for(var i=0; i<holidayz.length; i++){
if ((holidayz[i][1])==dvalue){
var mydate = new Date(dvalue);
console.log("<p>" + mydate + "<p>");
var day = mydate.getUTCDate();
var month = mydate.getMonth()+1;
var year = mydate.getFullYear();
console.log (month + "/" + day +"/" + year);
var holival= i; //asList(holidayz).indexOf(dvalue);
console.log(holival);
break;
}
}
}
console.log(txt);
}