Good evening! I have an assignment in school that requires me to:
Add a button that switches language from spanish to english.
And changing the DD:MM:YY Format, so i made a switch that changes them with each press of the button.
The problem is..... using this script...
'''
var inicioTiempo=0;
function fechaHora()
{
var cont=0;
dt=new Date();
var dia=["Domingo","Lunes","Martes","Miércoles","Jueves","Viernes","Sábado"];
var mes=["Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre"];
var hora=["12","1","2","3","4","5","6","7","8","9","10","11","12","1","2","3","4","5","6","7","8","9","10","11"];
var fyh=" "+dia[dt.getDay()]+" ";
switch (cont) {
case 0:
fyh=fyh+mes[dt.getMonth()]+" ";
fyh=fyh+dt.getDate()+" ";
fyh=fyh+dt.getFullYear();
cont=cont+1;
break;
case 1:
fyh=fyh+dt.getDate()+" ";
fyh=fyh+mes[dt.getMonth()]+" ";
fyh=fyh+dt.getFullYear();
cont=cont+1;
break;
case 2:
fyh=fyh+dt.getFullYear()+" ";
fyh=fyh+mes[dt.getMonth()]+" ";
fyh=fyh+dt.getDate();
cont=cont+1;
break;
case 3:
fyh=fyh+dt.getFullYear()+" ";
fyh=fyh+dt.getDate()+" ";
fyh=fyh+mes[dt.getMonth()];
cont=0;
break;
}
fyh=fyh+" <br> "+hora[dt.getHours()]+":"+dt.getMinutes()+":"+dt.getSeconds();
if(dt.getHours()>=0 && dt.getHours()<=11)
fyh=fyh+" a.m.";
else
fyh=fyh+" p.m. ";
document.getElementById('labelFechaHora').innerHTML=fyh;
setTimeout("fechaHora()",100);
}
</script>
<body onLoad="fechaHora()" link="black" alink="black" vlink="black">
<div class="panel panel-default">
<div class="panel-body">
<center>
<br>
<font color="black"> <label id="labelFechaHora"/> </font> <br>
<font color="black"> <label id="labelFechaHoraENG"/> </font> <br>
<input type="button" value="Ingles" onclick="fechaHoraENG();">
<input type="button" value="Español" onclick="fechaHora();">
'''
When i try to press once again the button, the script does not change at all, and the other one remains there.
1- Edit so that: Each time i press the spanish/eng, one shows up and hides the other.
2- When i re'press, the DD:MM:YY change (Asuming i had one function per language)
Below is an example of Object Oriented, mixed with Functional, Programming in JavaScript. I decided you didn't really want just an increment that is looped over time. Instead you want to be able to select a language and a format.
function FechaHora(){
let dt = new Date;
const dia = ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'];
const mes = ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'];
this.updateDate = ()=>{
dt = new Date;
return this;
}
const formatIt = (format, array)=>{
let m = array[dt.getMonth()], d = dt.getDate(), y = dt.getFullYear();
switch(format.toLowerCase()){
case 'mdy':
return m+' '+d+' '+y;
case 'dmy':
return d+' '+m+' '+y;
case 'ymd':
return y+' '+m+' '+d;
case 'ydm':
return y+' '+d+' '+m;
}
}
this.fechaDia = format=>{
return formatIt(format, dia);
}
this.fechaMes = format=>{
return formatIt(format, mes);
}
this.fechaTime = ()=>{
let h = dt.getHours(), m = dt.getMinutes(), s = dt.getSeconds(), p = 'a.m.';
if(h > 12){
h -= 12; p = 'p.m.';
}
if(m < 10)m = '0'+m;
if(s < 10)s = '0'+s;
return h+':'+m+':'+s+' '+p;
}
}
let doc, html, bod, I; // for use on other loads
addEventListener('load', ()=>{
doc = document; html = doc.documentElement; bod = doc.body; I = id=>doc.getElementById(id);
const date = I('date'), time = I('time'), lang = I('lang'), format = I('format');
const fa = new FechaHora;
let ti;
function output(){
let v = format.value;
fa.updateDate();
switch(lang.value){
case 'dia':
date.textContent = fa.fechaDia(v);
break;
case 'mes':
date.textContent = fa.fechaMes(v);
break;
}
time.textContent = fa.fechaTime();
}
function run(milliseconds = 1000){
if(ti)clearInterval(ti);
output(); ti = setInterval(output, milliseconds);
}
run();
lang.onchange = format.onchange = e=>{
run();
}
}); // end load
*{
box-sizing:border-box;
}
<div id='date'></div>
<div id='time'></div>
<select id='lang'>
<option value='dia'>Dia</option>
<option value='mes'>Mes</option>
</select>
<select id='format'>
<option value='mdy'>M D Y</option>
<option value='dmy'>D M Y</option>
<option value='ymd'>Y M D</option>
<option value='ydm'>Y D M</option>
</select>
Related
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>
I have poured over this code and I feel pretty positive about it. That being said, something is obviously missing, as the program itself comes up with an empty clock when run in the browser. I know that the brackets and parentheses all have a matching set, and I am fairly confident in my functions. The chrome developer tools were unhelpful. Anyone with a good eye for Javascript able to see what is missing here?
"use strict";
var $ = function(id) {
return document.getElementById(id);
};
var displayCurrentTime = function() {
var today = new Date();
var hour = today.getHours();
var min = today.getMinutes();
var sec today.getSeconds();
var ap = "AM";
if (hour > 12) {
h = h - 12;
ap = "PM";
} else {
switch (hour) {
case 12:
ap = "PM";
break;
case 0:
ap = "AM";
break;
}
}
$("hours").firstChild.nodeValue = padSingleDigit(hours);
$("minutes").firstChild.nodeValue = padSingleDigit(min);
$("seconds").firstChild.nodeValue = padSingleDigit(sec);
$("ap").firstChild.nodeValue = padSingleDigit(ap);
};
var padSingleDigit = function(num) {
if (num < 10) {
return "0" + num;
} else {
return num;
}
};
window.onload = function() {
displayCurrentTime();
setInterval(displayCurrentTime, 1000);
};
<html>
<head>
<meta charset="UTF-8">
<title>Clock</title>
<link rel="stylesheet" href="clock.css">
<script src="clock.js"></script>
</head>
<body>
<main>
<h1>Digital clock</h1>
<fieldset>
<legend>Clock</legend>
<span id="hours"> </span>:
<span id="minutes"> </span>:
<span id="seconds"> </span>
<span id="ampm"> </span>
</fieldset>
</main>
</body>
</html>
You simply have a lot of (3) typos ...
"use strict";
var $ = function(id) {
return document.getElementById(id);
};
var displayCurrentTime = function() {
var today = new Date();
var hour = today.getHours();
var min = today.getMinutes();
var sec = today.getSeconds();
var ap = "AM";
if (hour > 12) {
hour = hour - 12;
ap = "PM";
} else {
switch (hour) {
case 12:
ap = "PM";
break;
case 0:
ap = "AM";
break;
}
}
$("hours").firstChild.nodeValue = padSingleDigit(hour);
$("minutes").firstChild.nodeValue = padSingleDigit(min);
$("seconds").firstChild.nodeValue = padSingleDigit(sec);
$("ampm").firstChild.nodeValue = padSingleDigit(ap);
};
var padSingleDigit = function(num) {
if (num < 10) {
return "0" + num;
} else {
return num;
}
};
window.onload = function() {
displayCurrentTime();
setInterval(displayCurrentTime, 1000);
};
<main>
<h1>Digital clock</h1>
<fieldset>
<legend>Clock</legend>
<span id="hours"> </span>:
<span id="minutes"> </span>:
<span id="seconds"> </span>
<span id="ampm"> </span>
</fieldset>
</main>
*there are other (non-functional) problems in this code, but since it is not the Q, I'd not change them to keep this answer on point.
I have just started learning javascript and i am stuck with my first lab. I have the HTML part working but none of the javascript is working. At first I thought it did not link the javascript code to the HTML code correctly but now i think there is issues with the onload and oninput part. But have no idea why. If someone can help would be appreciated.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Lab 11 suits</title>
<script src="Lab1.js"></script>
</head>
<body>
<heading>
<h1>
HTML 5 Test Page
</h1>
</heading>
<p id="test"></p>
<button id="button">Press Me</button>
<p/>
Colours:<select id="list">
<option>Red</option>
<option>Green</option>
<option>Blue</option>
</select>
<p/>
Your Birthday:<input type="date" id="dod"/>
A Number: <input type="range" id="range" min="1" max="10" value="1">
<span id="value">1</span>
</body>
</html>
window.onload = function() {
var para = document.getElementById("heading");
para.innerText = "A short exercise on creating dynamic web content.";
var button = document.getElementById("button");
button.onclick = function () {
alert("Ive been clicked");
};
var list = document.getElementById("list");
list.onchange = function () {
var item = list.options[list.selectedIndex].text;
changeColour(item);
};
var dob = document.getElementById("dob");
dob.oninput = function () {
alert("Your birth date is:" + dob.value);
};
var range = document.getElementById("range");
var value = document.getElementById("value");
range.onchange = function () {
value.innerText = range.value;
};
function changeColour(colour) {
var c = 0;
switch (colour) {
case "Red":
c = "#f00";
break;
case "Green":
c = "#0f0";
break;
case "Blue":
c = "#00f";
break;
}
document.bgColor = c;
};
function daysOld(dob) {
var msPerDay = 1000 * 60 * 60 * 24,
now = new Date(),
diff = now - dob;
return diff / msPerDay;
};
};
I have made a couple of edits:
Missing id on the heading element
typo on the id="dob" you had id="dod"
window.onload = function() {
/******* EDIT 1 ********/
// the heading element has no ID, so you need to add one, or use `querySelector` instead.
//var para = document.getElementById("heading");
var para = document.querySelector("heading");
/***********************/
para.innerText = "A short exercise on creating dynamic web content.";
var button = document.getElementById("button");
button.onclick = function () {
alert("Ive been clicked");
};
var list = document.getElementById("list");
list.onchange = function () {
var item = list.options[list.selectedIndex].text;
changeColour(item);
};
var dob = document.getElementById("dob");
dob.oninput = function () {
alert("Your birth date is:" + dob.value);
};
var range = document.getElementById("range");
var value = document.getElementById("value");
range.onchange = function () {
value.innerText = range.value;
};
function changeColour(colour) {
var c = 0;
switch (colour) {
case "Red":
c = "#f00";
break;
case "Green":
c = "#0f0";
break;
case "Blue":
c = "#00f";
break;
}
document.bgColor = c;
};
function daysOld(dob) {
var msPerDay = 1000 * 60 * 60 * 24,
now = new Date(),
diff = now - dob;
return diff / msPerDay;
};
};
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Lab 11 suits</title>
<script src="Lab1.js"></script>
</head>
<body>
<heading>
<h1>
HTML 5 Test Page
</h1>
</heading>
<p id="test"></p>
<button id="button">Press Me</button>
<p/>
Colours:<select id="list">
<option>Red</option>
<option>Green</option>
<option>Blue</option>
</select>
<p/>
<!-- EDIT 2 -->
<!-- You had a typo on the id of your input 'dod' -> 'dob' -->
<!-- Your Birthday:<input type="date" id="dod"/> -->
Your Birthday:<input type="date" id="dob"/>
<!-- End EDIT -->
A Number: <input type="range" id="range" min="1" max="10" value="1">
<span id="value">1</span>
</body>
</html>
I have made this function here to calculate prices from choices in the select menu. I have made a switch but I dont understand where to input my function to trigger it (on html). The 2 other functions changeit() and changerepas() are onchange functions that will give you the basic price. (they are not linked to the question) (Note: This is my first switch ever, so it might look noobish to most of you. )
function taxesrepas(option){
var soustot;
var taxes;
var taxer;
var taxetotal = taxes + taxer;
var total = taxetotal + soustot;
var pricee;
var pricer;
var soustot = pricee + pricer;
switch (option){
case "spaghetti":
taxer = 0.69;
pricer = 8.95
break;
case "lasagne":
taxer = 0.75;
pricer = 9.95;
break;
case "salade":
taxes = 0.45;
pricee = 5.95;
break;
case "escargot":
taxes = 0.38;
pricee = 4.95;
break;
}
document.getElementById("taxes").innerHTML = taxetotal;
document.getElementbyid("total").innerHTML = total;
document.getElementbyid("soustot").innerHTML = soustot;
}
<select name="entree" id="entree" onChange="changeit(this.value)">
<option value="hidden" selected>Choisir...</option>
<option value="salade">Salade</option>
<option value="escargot">Escargot</option>
</select>
<img display="inline" id="imgselect" src="" alt="0.00$"/>
<h3 id= "choix1"></h3>
<p>Repas</p>
<select name="repas" id="repas" onChange="changerepas(this.value)">
<option value="hidden1" selected>Choisir...</option>
<option value="spaghetti">Spaghetti</option>
<option value="lasagne">Lasagne</option>
</select>
<h3 id="choix"></h3>
<h3 id="taxes"></h3>
<h3 id="soustotal"></h3>
<h3 id="total"></h3>
Maybe change the onChange to
function(){
taxesrepas(this.value);
changeit(this.value);
}
I am back. How am I suppose to change a select content if I choose an option of other select. This is my JSFiddle. What I want is that if I select the 'mes' = 2 option (february). It shows me only 28 days on the 'dia' select (days). I don't know how to refer when the number 2 is selected so I can build a if structure. Thx in advance, my english is not the best... (I don't wanna use JQuery)
This is my whole HTML:
<p>Dia
<select name="dia" id="dia"></select>Mes
<select name="mes1" id="mes"></select>Año
<select name="año" id="año"></select>
</p>
<p>
<input type="text" name="txtFecha1" id="txtFecha1" disabled/>
<input type="submit" name="capturar" id="capturar" value="Capturar" onclick="capturar()" />
</p>
<p>
<input type="text" name="txtFecha2" id="txtFecha2" disabled/>
<input type="submit" name="capturar2" id="capturar2" value="Capturar" onclick="capturar()" />
</p>
<p>
<input type="submit" name="diferencia" id="diferencia" value="Diferencia" onclick="diferencia()" />
</p>
<p id="pParrafo">Dias entre las fechas:</p>
onClick functions are not programmed yet.
This is the JS:
var mes = new Array();
for (i = 1; i <= 12; i++) {
mes[i] = i;
}
var seleccionar = document.getElementById('mes');
for (var i = 1; i < mes.length; i++) {
var option = document.createElement('option');
option.innerHTML = mes[i];
option.value = mes[i];
seleccionar.appendChild(option);
}
var año = new Array();
for (i = 1950; i <= 2014; i++) {
año[i] = i;
}
var seleccionar = document.getElementById('año');
for (var i = 1950; i < año.length; i++) {
var option = document.createElement('option');
option.innerHTML = año[i];
option.value = año[i];
seleccionar.appendChild(option);
}
Here's a simple example of how I'd do it: add and remove options from the days select based on the year and month selected. It doesn't create or destroy options, it just moves them around.
It's less code and more efficient than alternatives.
<script>
// Simple function to return days in month given year and month
// Month is calendar number, e.g. 1 = jan, 2 = feb, etc.
function daysInMonth(year, month) {
return new Date(year, month, 0).getDate();
}
// Update the number of options in the day select
var updateDay = (function() {
// Document fragment to store spare options
var frag = document.createDocumentFragment();
return function(control) {
// Get a reference to the form and day select
var form = control.form;
var daySelect = form.day;
// Get days in month based on year and month selected
var days = daysInMonth(form.year.value, form.month.value);
// Remove or restore days to correct number
while(daySelect.options.length != days) {
daySelect.options.length > days? frag.appendChild(daySelect.lastChild) :
daySelect.appendChild(frag.lastChild);
}
}
}());
</script>
<!-- Simple date selector -->
<form>
Year: <select name="year" onchange="updateDay(this)">
<option value="2010">2010
<option value="2011">2011
<option value="2012">2012
<option value="2013">2013
<option value="2014">2014
</select>
Month: <select name="month" onchange="updateDay(this)">
<option value="1">Jan
<option value="2">Feb
<option value="3">Mar
<option value="4">Apr
<option value="5">May
<option value="6">Jun
<option value="7">Jul
<option value="8">Aug
<option value="9">Sep
<option value="10">Oct
<option value="11">Nov
<option value="12">Dec
</select>
Day: <select name="day">
<script>
// Saves on markup...
for (var i=1; i<32; i++) {
document.write('<option value="' + i + '">' + i + '<\/option>');
console.log(i);
}
</script>
</select>
</form>
youcan set filldia function on change of month select element
try this code :
HTML :
<select name="mes1" id="mes" onchange="fillDia(this)"
Javascript
// generate dia items
var dia = new Array();
fillDia(document.getElementById('mes'));
function fillDia(opt) {
// empty dia select element options
document.getElementById('dia').options.length = 0;
var maxDays = 31;
//alert (opt.value);
if (opt.value == '2') maxDays = 28; //feburary
if (opt.value == '4' || opt.value == '6' || opt.value == '9' || opt.value == '11') maxDays = 30; //april , june , september , november
for (i = 1; i <= maxDays; i++) {
dia[i] = i;
}
//se guarda el select dia
var dias = document.getElementById('dia');
//generar select para dia
for (var i = 1; i <= maxDays; i++) {
var option = document.createElement('option');
option.innerHTML = dia[i];
option.value = dia[i];
dias.appendChild(option);
}
}
JSFIDDLE DEMO