Not displaying sections with javascript calendar - javascript

I need to display a calendar on the homepage and have staff add their birthdays to the calendar but it's not displaying the dates, duration and Name section.
Here is the code for the homepage (excluding css files etc.)
<!DOCTYPE html>
<html lang="en">
<head>
<link href="bootstrap.css" rel="stylesheet" />
<link href="bootstrap.min.css" rel="stylesheet" />
<link href="style.css" rel="stylesheet" />
<link href="bootstrap-responsive.css" rel="stylesheet" />
<link href="bootstrap-responsive.min.css" rel="stylesheet" />
<link href="bootstrap.css" rel="stylesheet" />
<link href="bootstrap.min.css" rel="stylesheet" />
<script src="bootstrap.js"></script>
<script src="bootstrap.min.js"></script>
<script src="lightbox.js"></script>
<link href="lightbox.css" rel="stylesheet" />
<style>
body {
font-family: Verdana, sans-serif;
margin: 0;
}
* {
box-sizing: border-box;
}
.row > .column {
padding: 0 8px;
}
.row:after {
content: "";
display: table;
clear: both;
}
.column {
float: left;
width: 25%;
}
/* The Modal (background) */
.modal {
display: none;
position: fixed;
z-index: 1;
padding-top: 100px;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: black;
}
/* Modal Content */
.modal-content {
position: relative;
background-color: #fefefe;
margin: auto;
padding: 0;
width: 90%;
max-width: 1200px;
}
/* The Close Button */
.close {
color: white;
position: absolute;
top: 10px;
right: 25px;
font-size: 35px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: #999;
text-decoration: none;
cursor: pointer;
}
.mySlides {
display: none;
}
.cursor {
cursor: pointer
}
/* Next & previous buttons */
.prev,
.next {
cursor: pointer;
position: absolute;
top: 50%;
width: auto;
padding: 16px;
margin-top: -50px;
color: white;
font-weight: bold;
font-size: 20px;
transition: 0.6s ease;
border-radius: 0 3px 3px 0;
user-select: none;
-webkit-user-select: none;
}
/* Position the "next button" to the right */
.next {
right: 0;
border-radius: 3px 0 0 3px;
}
/* On hover, add a black background color with a little bit see-through */
.prev:hover,
.next:hover {
background-color: rgba(0, 0, 0, 0.8);
}
/* Number text (1/3 etc) */
.numbertext {
color: #f2f2f2;
font-size: 12px;
padding: 8px 12px;
position: absolute;
top: 0;
}
img {
margin-bottom: -4px;
}
.caption-container {
text-align: center;
background-color: black;
padding: 2px 16px;
color: white;
}
.demo {
opacity: 0.6;
}
.active,
.demo:hover {
opacity: 1;
}
img.hover-shadow {
transition: 0.3s
}
.hover-shadow:hover {
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19)
}
</style>
</head>
<body>
<div id="page">
<nav align="center">
<br /><img src="images/logo.png" /><br /><br />
Home |
Create Meeting |
Join Meeting
</nav>
<div class="clearfix"><br /><br /></div>
<div class="row">
<div class="column">
<img src="images/img1.jpg" style="width:100%" onclick="openModal();currentSlide(1)" class="hover-shadow cursor">
</div>
<div class="column">
<img src="images/img2.jpg" style="width:100%" onclick="openModal();currentSlide(2)" class="hover-shadow cursor">
</div>
<div class="column">
<img src="images/img3.jpg" style="width:100%" onclick="openModal();currentSlide(3)" class="hover-shadow cursor">
</div>
<div class="column">
<img src="images/img4.jpg" style="width:100%" onclick="openModal();currentSlide(4)" class="hover-shadow cursor">
</div>
<div class="column">
<br /><img src="images/img6.jpg" align="right" style="width:100%" onclick="openModal();currentSlide(5)" class="hover-shadow cursor">
</div>
</div>
<div id="myModal" class="modal">
<span class="close cursor" onclick="closeModal()">×</span>
<div class="modal-content">
<div class="mySlides">
<div class="numbertext">1 / 5</div>
<img src="images/img1.jpg" style="width:100%">
</div>
<div class="mySlides">
<div class="numbertext">2 / 5</div>
<img src="images/img2.jpg" style="width:100%">
</div>
<div class="mySlides">
<div class="numbertext">3 / 5</div>
<img src="images/img3.jpg" style="width:100%">
</div>
<div class="mySlides">
<div class="numbertext">4 / 5</div>
<img src="images/img4.jpg" style="width:100%">
</div>
<div class="mySlides" align="center">
<div class="numbertext">5 / 5</div>
<br /><br /><img src="images/img6.jpg" style="width:100%">
</div>
<a class="prev" onclick="plusSlides(-1)">❮</a>
<a class="next" onclick="plusSlides(1)">❯</a>
<div class="caption-container">
<p id="caption"></p>
</div>
<div class="column">
<img class="demo cursor" src="images/img1.jpg" style="width:100%" onclick="currentSlide(1)" alt="">
</div>
<div class="column">
<img class="demo cursor" src="images/img2.jpg" style="width:100%" onclick="currentSlide(2)" alt="">
</div>
<div class="column">
<img class="demo cursor" src="images/img3.jpg" style="width:100%" onclick="currentSlide(3)" alt="">
</div>
<div class="column">
<img class="demo cursor" src="images/img4.jpg" style="width:100%" onclick="currentSlide(4)" alt="">
</div>
<div class="column">
<br /><br /><img class="demo cursor" src="images/img6.jpg" style="width:100%" onclick="currentSlide(5)" alt="" align="middle">
</div>
</div>
</div>
<script>
function openModal() {
document.getElementById('myModal').style.display = "block";
}
function closeModal() {
document.getElementById('myModal').style.display = "none";
}
var slideIndex = 1;
showSlides(slideIndex);
function plusSlides(n) {
showSlides(slideIndex += n);
}
function currentSlide(n) {
showSlides(slideIndex = n);
}
function showSlides(n) {
var i;
var slides = document.getElementsByClassName("mySlides");
var dots = document.getElementsByClassName("demo");
var captionText = document.getElementById("caption");
if (n > slides.length) { slideIndex = 1 }
if (n < 1) { slideIndex = slides.length }
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
for (i = 0; i < dots.length; i++) {
dots[i].className = dots[i].className.replace(" active", "");
}
slides[slideIndex - 1].style.display = "block";
dots[slideIndex - 1].className += " active";
captionText.innerHTML = dots[slideIndex - 1].alt;
}
</script>
<section align="left">
<img src="images/hdsplitter.png" align="middle" /><br /><br />
<h1 style="color:#0099ff">Welcome to <b>Systeque</b></h1>
<br />
<div class="col-lg-6 col-md-6 col-sm-6">
<div align="left">
<br />
<h3 style="color:#0099ff"><b>Who We Are</b></h3>
<p><b style="color:#0099ff">Systeque</b> was established in 1998 and has grown to be one of South Africa's leading IT Solution and Service Providers. Systeque is based in the Hyde Park, Sandton in Johannesburg. Systeque’s core focus is to provide total solutions to all customers by bringing new and innovative concepts and cost effective ideas to market. Our strengths lie in Infrastructure Architecture, Cloud Computing and Managed Services. Since inception, Systeque has developed in areas that have shown a definite market requirement. With implementations in all business sectors.</p>
<br /><h3 style="color:#0099ff"><b>My role at the Company</b></h3>
<p>As Operations Manager my duties include co-ordination of our technical team to ensure daily operational functions of the business are running, this also entails ensuring the sales function of the business is processing quotations and orders in accordance with client requirements. Client relations being one of my key areas involves consulting with clients on their daily requirements and projects they are running or planning. Other vital areas of my role includes continous research into products, services and technologies that will further streamline our processes and grow our revenue.</p>
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-6">
<img src="images/img5.jpg" alt="service" width="450" />
<br /><br /><br />
</div>
</section>
<section align="center">
<h1 style="color:#0099ff"><b>Calender</b></h1>
</section>
</div>
And here is the code for the Assignment page
<html>
<head>
<script type ="text/javascript">
var celebration = new Array();
var months = new Array(12);
var times = new Array(9);
var duration = new Array(9);
var attends = new Array();
var mNum, yNum, dNum, smon, sdate, dif, stimes, sdur;
var Cname, Cmonth, Cdate, Ctime, Cduration, Cvenue, Cnum, Crefresh;
function upDate()
{
document.f1.date.length = 0;
var j;
var mSel = document.f1.month.selectedIndex;
mSel = mSel + mNum;
if((mSel>11) && (mSel<=14))
{
mSel = mSel - 12;
}
if((mSel===0) || (mSel==2) || (mSel==4) || (mSel==6) || (mSel==7) || (mSel==9) || (mSel==11))
{
j = 31;
}
else if((mSel==3) || (mSel==5) || (mSel==8) || (mSel==10))
{
j = 30;
}
else if(mSel==1)
{
if((yNum%4)===0)
{
j = 29;
}
else
{
j = 28;
}
}
else
{
alert("Error with system time");
}
for(var i=0; i<j; i++)
{
var opt = new Option(i+1, i+1, false, false);
document.f1.date.options[i] = opt;
}
if(document.f1.month.selectedIndex===0)
{
for(i=(dNum-1); i>=0; i--)
{
document.f1.date.options[i] = null;
}
if(document.f1.date.length===0)
{
document.f1.month.options[0].disabled = true;
document.f1.month.selectedIndex = 1;
upDate();
}
}
if(document.f1.month.selectedIndex==3)
{
document.f1.date.length = 0;
var dn = dNum;
if(dn>j)
{
dn = j;
}
for(;i<dn; i++)
{
var opt = new Option(i+1, i+1, false, false);
document.f1.date.options[i] = opt;
}
}
capture();
}
function validate()
{
capture();
if(Cname==="")
{
alert("Celebration cannot be created - Name required");
document.f1.n.focus();
}
else if(Cnum==="")
{
alert("Celebration cannot be created - Description required");
document.f1.num.focus();
}
else if(Cvenue==="")
{
alert("Celebration cannot be created - Venue required");
document.f1.ven.focus();
}
else
{
bookCelebration();
}
}
function capture()
{
Cname = document.f1.n.value;
Cnum = document.f1.num.value;
Cmonth = document.f1.month.selectedIndex;
Cmonth = document.f1.month.options[Cmonth].value;
Cmonth = months[Cmonth];
Cdate = document.f1.date.selectedIndex;
Cdate = document.f1.date.options[Cdate].value;
Ctime = document.f1.time.selectedIndex;
Ctime = document.f1.time.options[Ctime].value;
Cduration = document.f1.dur.selectedIndex;
Cduration = document.f1.dur.options[Cduration].value;
Cvenue = document.f1.ven.value;
if(document.f1.refresh.checked === true)
{
Crefresh = "true";
}
else
{
Crefresh = "false";
}
}
function bookMeeting()
{
var index = meetings.length;
meetings[index] = new Array(8);
celebration[index][0] = Cname;
celebration[index][1] = Cnum;
celebration[index][2] = Cmonth;
celebration[index][3] = Cdate;
celebration[index][4] = Ctime;
celebration[index][5] = Cduration;
celebration[index][6] = Cvenue;
celebration[index][7] = Crefresh;
addBooking(index);
}
function addBooking(index)
{
var opt = new Option(Cname, Cnum, Cmonth, Cdate, Ctime, Cduration, Cvenue, Crefresh);
document.f2.nm.options[index] = opt;
alert("Booking successful");
clearInput();
if(celebration.length===0)
{
document.f2.v.disabled = true;
}
else
{
document.f2.v.disabled = false;
}
}
function search()
{
var inp = document.f2.nm.selectedIndex;
var pos;
inp = celebration[inp][0];
for(var i=0; i<celebration.length; i++)
{
if (inp==celebration[i][0])
{
pos = i;
}
}
document.f1.n.value = celebration[pos][0];
document.f1.num.value = celebration[pos][1];
smon = celebration[pos][2];
for (var j=0; j<months.length; j++)
{
if(months[j] == smon)
{
smon = j;
}
}
smon = smon - mNum;
document.f1.month.selectedIndex = smon;
upDate();
sdate = celebration[pos][3];
if (smon===0)
{
dif = sdate - dNum;
dif = dif -1;
}
else
{
dif = sdate - 1;
}
document.f1.date.selectedIndex = dif;
stimes = celebration[pos][4];
for (; j<times.length; j++)
{
if(times[j] == stimes)
{
stimes = j;
}
}
document.f1.time.selectedIndex = stimes;
sdur = celebration[pos][5];
for (; j<duration.length; j++)
{
if(duration[j] == sdur)
{
sdur = j;
}
}
document.f1.dur.selectedIndex = sdur;
document.f1.ven.value = celebration[pos][6];
if(celebration[pos][7]=="true")
{
document.f1.refresh.checked = true;
}
else if(celebration[pos][7]=="false")
{
document.f1.refresh.checked = false;
}
document.f2.join.disabled = false
}
function joinCelebration()
{
var index = attends.length;
attends[index] = new Array(5);
attends[index][0] = window.prompt("Enter first name");
attends[index][1] = window.prompt("Enter surname");
attends[index][2] = window.prompt("Enter email address");
attends[index][3] = window.prompt("Enter office number");
attends[index][4] = window.prompt("Enter celebration name");
var x = document.f2.nm.selectedIndex;
attends[index][4] = document.f2.nm.options[x].value;
y = attends[index][4];
var nat = 0;
for(var a=0; a<attends.length;a++)
{
if(attends[a][4] = y)
{
nat = nat +1;
}
}
document.f3.atnd.value = nat;
var g = celebration[index][5];
var drt;
for (var h=0; h<duration.length; h++)
{
if(duration[h] == g)
{
drt = h;
}
}
if(drt < 2)
{
document.f3.sgref.value = "Tea & Biscuits";
}
else if(drt < 4)
{
document.f3.sgref.value = "Finger Lunch";
}
else
{
document.f3.sgref.value = "Sit down Lunch";
}
clearInput();
}
function popMonths()
{
months[1] = "January";
months[2] = "February";
months[3] = "March";
months[4] = "April";
months[5] = "May";
months[6] = "June";
months[7] = "July";
months[8] = "August";
months[9] = "September";
months[10] = "October";
months[11] = "November";
months[12] = "December";
}
function popDuration()
{
duration[0] = "30 mins";
duration[1] = "1 hour";
duration[2] = "2 hours";
duration[3] = "3 hours";
duration[4] = "4 hours";
duration[5] = "5 hours";
duration[6] = "6 hours";
duration[7] = "7 hours";
duration[8] = "8 hours";
}
function curDate()
{
var now = new Date();
mNum = now.getMonth();
yNum = now.getFullYear();
dNum = now.getDate();
}
function updateMonth()
{
var opt1 = new Option(months[mNum], mNum, false, false);
document.f1.month.options[0] = opt1;
var opt2 = new Option(months[mNum + 1], mNum + 1, false, false);
document.f1.month.options[1] = opt2;
var opt3 = new Option(months[mNum + 2], mNum + 2, false, false);
document.f1.month.options[2] = opt3;
var opt4 = new Option(months[mNum + 3], mNum + 3, false, false);
document.f1.month.options[3] = opt4;
}
function upDate()
{
document.f1.date.length = 0;
var j;
var mSel = document.f1.month.selectedIndex;
mSel = mSel + mNum;
if((mSel>11) && (mSel<=14))
{
mSel = mSel - 12;
}
if((mSel===0) || (mSel==2) || (mSel==4) || (mSel==6) || (mSel==7) || (mSel==9) || (mSel==11))
{
j = 31;
}
else if((mSel==3) || (mSel==5) || (mSel==8) || (mSel==10))
{
j = 30;
}
else if(mSel==1)
{
if((yNum%4)===0)
{
j = 29;
}
else
{
j = 28;
}
}
else
{
alert("Error with system time");
}
for(var i=0; i<j; i++)
{
var opt = new Option(i+1, i+1, false, false);
document.f1.date.options[i] = opt;
}
if(document.f1.month.selectedIndex===0)
{
for(i=(dNum-1); i>=0; i--)
{
document.f1.date.options[i] = null;
}
if(document.f1.date.length===0)
{
document.f1.month.options[0].disabled = true;
document.f1.month.selectedIndex = 1;
upDate();
}
}
if(document.f1.month.selectedIndex==3)
{
document.f1.date.length = 0;
var dn = dNum;
if(dn>j)
{
dn = j;
}
for(; i<dn; i++)
{
var opt = new Option(i+1, i+1, false, false);
document.f1.date.options[i] = opt;
}
}
capture();
}
function popTimes()
{
times[0] = "8:00am";
times[1] = "9:00am";
times[2] = "10:00am";
times[3] = "11:00am";
times[4] = "12:00pm";
times[5] = "1:00pm";
times[6] = "2:00pm";
times[7] = "3:00pm";
times[8] = "4:00pm";
}
function upTimes()
{
for(var i=0; i<times.length; i++)
{
var opt = new Option(times[i]);
document.f1.time.options[i] = opt;
}
}
function upDur()
{
for(var i=0; i<duration.length; i++)
{
var opt = new Option(duration[i]);
document.f1.dur.options[i] = opt;
}
}
function clearInput()
{
initialize();
document.f1.n.value = "";
document.f1.num.value = "";
document.f1.ven.value = "";
document.f1.refresh.checked = false;
}
function initialize()
{
popMonths();
popTimes();
curDate();
popDuration();
updateMonth();
upDate();
upTimes();
upDur();
document.f1.n.focus();
if(celebration.length===0)
{
document.f2.v.disabled = true;
}
else
{
document.f2.v.disabled = false;
}
}
</script>
</head>
<body onload = "initialize()">
<form name = "f1">
<h1> Create a celebration </h1>
<table border = "0" cellpadding = "5">
<tr>
<td>
Birthday of
<input type = "text" name = "n"/>
</td>
</tr>
<tr>
<td>
Birthday Message
<input type = "text" name = "num" onchange = "capture()"/>
</td>
</tr>
<tr>
<td>
Date: Month
<select name = "month" onchange = "upDate()"/>
<option value = "0">
Nothing
</option>
</select>
</td>
<td>
Date
<select name = "date" onchange = "capture()"/>
<option value = "0">
Nothing
</option>
</select>
</td>
</tr>
<tr>
<td>
Time
<select name = "time" onchange = "capture()"/>
<option value = "0">
Nothing
</option>
</select>
</td>
<td>
Duration
<select name = "dur" onchange = "capture()"/>
<option value = "0">
Nothing
</option>
</select>
</td>
</tr>
<tr>
<td>
Venue
<input type = "text" name = "ven" onchange = "capture()"/>
</td>
<td>
Refreshments
<input type = "checkbox" name = "refresh" onchange = "capture()" onclick = "capture()"/>
</td>
</tr>
<tr>
<td align = "center">
<input type = "button" value = "Create" onclick = "validate()"/>
</td>
<td align = "right">
<input type = "button" name = "del" value = "Delete" disabled = "true" onclick = "deleteBooking()"/>
<input type = "button" value = "Clear" onclick = "clearInput()"/>
</td>
</tr>
</table>
</form>
<form name = "f2">
<h1> Sign-up for celebration </h1>
<table border = "0" cellpadding = "5">
<tr>
<td>
Name
<select name = "nm"/>
<option value = "0">
None
</option>
</select>
</td>
</tr>
<tr>
<td align = "center">
<input type = "button" value = "Search" name = "v"onclick = "search()"/>
</td>
<td align = "center">
<input type = "button" name = "join" value = "Join" disabled = "true"/ onclick = "joinCelebration()">
</td>
</tr>
</table>
</form>
<form name = "f3">
<h1>Celebration details</h1>
<table border = "0" cellpadding = "5">
<tr>
<td>
Number of attendees
<input type = "text" name = "atnd"/>
</td>
</tr>
<tr>
<td>
Suggested refreshments
<input type = "text" name = "sgref"/>
</td>
</tr>
</table>
</form>
</body>
</html>
When you click on any dropdown it says "nothing" instead of the options.

this probably because you are missing the jquery file. jquery is a must when you used bootstrap. have you check the Starter template here: http://getbootstrap.com/docs/4.1/getting-started/introduction/

Found the solution - the reason the dropdowns were not showing the options from the JavaScript code was because testing against 0 needs to have ===.
if((mSel===0) || (mSel==2) || (mSel==4) || (mSel==6) || (mSel==7) || (mSel==9) || (mSel==11))
{
Now however the calander does not show on the home page. The assignment page needs to be a page to create birthday celebrations for staff members and the home page must have calendar showing links to celebrations that have already been created.
That is the main thing so it needs capture and show it.

Related

How to sort `divs` based on user's number of clicks using JS?

I'm using a script that counts how many times the user clicks each link and sort their order based on that number...
It works fine as is, however it doesn't work if the <a> tags is nested inside a div. It's ignoring the divs and the content/image/icon inside, while showing only the links..
How to change it so that it will show and reorder the entire div instead of just the link?
Please see what I have so far:
function updateClicks(ele) {
const storage = window.localStorage.getItem(ele.innerHTML + " clicks");
if (storage === null) {
window.localStorage.setItem(ele.innerHTML + " clicks", "1");
} else {
var clicks = parseInt(window.localStorage.getItem(ele.innerHTML + " clicks")) + 1;
localStorage.removeItem(ele.innerHTML + " clicks");
window.localStorage.setItem(ele.innerHTML + " clicks", clicks);
}
}
function orderItems() {
var order = [];
var href = [];
var links = document.getElementById("links-list");
var link = links.getElementsByTagName("a");
for (i = 0; i < link.length; i++) {
href.push(link[i].href);
}
links = links.innerHTML.split("</a>");
document.getElementById("links-list").innerHTML = "";
for (i = 0; i < links.length - 1; i++) {
var lastChar = links[i].charAt(links[i].length - 1);
var clicks = parseInt(window.localStorage.getItem(lastChar + " clicks"));
if (isNaN(clicks)) {
clicks = 0;
}
order.push([lastChar, clicks, href[i]]);
}
order.sort(function(a, b) {
return a[1] - b[1]
});
order.reverse();
console.log(order)
for (i = 0; i < order.length; i++) {
document.getElementById("links-list").innerHTML += "<a href='" + order[i][2] + "' onclick='updateClicks(this)'>" + order[i][0] + "</a>";
}
}
.link-container {
display: inline-block;
}
.link-container a {
padding: 10px;
background-color: #c0c0c0;
}
.link-img {
width: 16px;
height: 16px;
}
<body onload="orderItems();">
<div id="links-list">
<div class="card link-container">
<img class="link-img" src="https://i.imgur.com/6ZpMxiG.png" />
A
</div>
<div class="card link-container">
<img class="link-img" src="https://i.imgur.com/sFUFOyO.png" />
B
</div>
<div class="card link-container">
<img class="link-img" src="https://i.imgur.com/M5a2gh8.png" />
C
</div>
<div class="card link-container">
<img class="link-img" src="https://i.imgur.com/mbrEuvR.png" />
D
</div>
</div>
</body>
I'm still trying to learn JS and I need this feature for a project I'm building.. Thank you in advance for any help.
Here is one way of keeping track of the click counts and sorting the divs accordingly:
// The cnt values in the divs array could be initialised from local storage:
const
list=document.getElementById("links-list"),
divs=[...list.querySelectorAll(".card")];
divs.forEach(e=>e.cnt=0)
list.onclick=ev=>{
if (ev.target.tagName!=="A") return;
ev.target.closest(".card").cnt++;
divs.sort((a,b)=>a.cnt-b.cnt)
.forEach(el=>list.append(el))
console.log(divs.map(e=>e.textContent.trim()+e.cnt).join(","))
}
.link-container {
display: inline-block;
border:1px solid grey;
}
.link-img {
width: 16px;
height: 16px;
}
<body">
<div id="links-list">
<div class="card link-container">
<img class="link-img" src="https://i.imgur.com/6ZpMxiG.png" />
A
</div>
<div class="card link-container">
<img class="link-img" src="https://i.imgur.com/sFUFOyO.png" />
B
</div>
<div class="card link-container">
<img class="link-img" src="https://i.imgur.com/M5a2gh8.png" />
C
</div>
<div class="card link-container">
<img class="link-img" src="https://i.imgur.com/mbrEuvR.png" />
D
</div>
</div>
</body>

Button array is empty after I copied from another array that has the whole set of HTMLCollection

I want to store all the existing button names into an array(copyAllButtons) by using the push function.
However, after the for-loop, there is still nothing inside copyAllButtons.
I am trying to make a reset function that required the array(copyAllButtons) to restore all the button names saved.
Can anyone help me? Thank you.
var all_buttons = document.getElementsByTagName('button'); //all button names are saved
var copyAllButtons = [];
console.log(all_buttons);
for (let i = 0; i < all_buttons.length; i++) {
copyAllButtons.push(all_buttons[i].classList[1]);
}
console.log(copyAllButtons); //####Button array is empty####
This is my file:
https://drive.google.com/file/d/1qbAAHClxJhNQUFyvrSklbGwX9tbsEsL8/view?usp=sharing
message of console.log(copyAllButtons)
element inside all_buttons
code related:JS
//challenge4
var all_buttons = document.getElementsByTagName('button'); //all button names are saved
var copyAllButtons = [];
console.log(all_buttons);
for (let i = 0; i < all_buttons.length; i++) {
copyAllButtons.push(all_buttons[i].classList[1]);
}
console.log(copyAllButtons); //####Button array is empty####
function buttonColorChange(buttonThingy) {
if (buttonThingy.value === 'red') {
buttonsRed();
} else if (buttonThingy.value === 'green') {
buttonsGreen();
} else if (buttonThingy.value === 'reset') {
buttonsColorReset();
} else if (buttonThingy.value === 'random') {
randomColors();
}
}
function buttonsRed() {
for (let i = 0; i < all_buttons.length; i++) {
all_buttons[i].className = 'btn btn-danger';
}
}
function buttonsGreen() {
for (let i = 0; i < all_buttons.length; i++) {
all_buttons[i].className = 'btn btn-success';
}
}
function buttonsColorReset() { //##function that i am working on##
for (let i = 0; i < all_buttons.length; i++) {
all_buttons[i].classList.remove(all_buttons[i].classList[1]);
all_buttons[i].classList.add(copyAllButtons[i]);
}
}
function randomColors() {
for (let i = 0; i < all_buttons.length; i++) {
var x = Math.floor(Math.random() * 4);
var y = ['btn-primary', 'btn-danger', 'btn-warning', 'btn-success'];
all_buttons[i].className = 'btn ' + y[x];
}
}
HTML
<div class="container-4">
<h2 id="change-my-color">Challenge 4:Change the color of all buttons</h2>
<div class="flex-box-pick-color">
<form action="">
<select name="backdrop" id="background" onChange="buttonColorChange(this)">
<option value="random">Random</option>
<option value="red">Red</option>
<option value="green">Green</option>
<option value="reset">Reset</option>
</select>
</form>
<button class="btn btn-primary">Wee!</button>
<button class="btn btn-danger">Yahoo!</button>
<button class="btn btn-warning">Google!</button>
<button class="btn btn-success">Facebook!</button>
</div>
</div>
CSS:
.container-1, .container-2 , .container-3 ,.container-4{
border: 1px solid blue;
width:75%;
margin: 0 auto;
text-align: center;
}
.flex-box-container-1, .flex-box-container-2,.flex-box-rps,.flex-box-pick-color{
display:flex;
border:1px solid purple;
padding: 10px;
flex-wrap:wrap;
flex-direction: row;
justify-content: space-around;
}
All my code for reference:
javascript:
function ageInDays() {
var birthYear = prompt("What year were you born?")
var days = (2021 - birthYear) * 365
var h1 = document.createElement('h1')
var textAnswer = document.createTextNode('You are ' + days + ' days old')
h1.setAttribute('id', 'days');
h1.appendChild(textAnswer)
document.getElementById('flex-box-result').appendChild(h1)
}
function reset() {
document.getElementById('days').remove()
}
function generateCat() {
var image = document.createElement('img');
var div = document.getElementById('flex-cat-gen');
image.src = "https://thecatapi.com/api/images/get?format=src&type=gif&size=small";
div.appendChild(image);
}
//challenge3 rock paper scissors
function getRandomInt(max) {
return Math.floor(Math.random() * max);
}
function randToRpsInt() {
return Math.floor(Math.random() * 3);
}
function numberToChoice(number) {
return ['rock', 'paper', 'scissors'][number]
}
function rpsGame(yourChoice) {
var result;
console.log(yourChoice.id);
var humanChoice, botChoice;
var message
humanChoice = yourChoice.id;
botChoice = numberToChoice(randToRpsInt());
console.log(botChoice);
if (humanChoice === 'rock') {
if (botChoice === 'rock') {
result = "tie"
console.log("tie");
}
else if (botChoice === 'paper') {
result = "lost"
console.log("You Lost>_<");
}
else {
result = "win"
console.log("You Win OAO");
}
}
else if (humanChoice === 'paper') {
if (botChoice === 'rock') {
result = "win";
console.log("You Win OAO");
}
else if (botChoice === 'scissors') {
result = "lost";
console.log("You Lost>_<");
}
else {
result = "tie";
console.log("tie");
}
}
//scissors
else {
if (botChoice === 'paper') {
result = "win";
console.log("You Win OAO");
}
else if (botChoice === 'rock') {
result = "lost";
console.log("You Lost>_<");
}
else {
result = "tie";
console.log("tie");
}
}
message = finalMessage(result);
rpsFrontEnd(humanChoice, botChoice, message);
}
function finalMessage(result) {
if (result === "lost")
return { 'message': 'You lost!', 'color': 'red' };
else if (result === "win")
return { 'message': 'You won!', 'color': 'green' };
else
return { 'message': 'You tied!', 'color': 'yellow' };
}
function rpsFrontEnd(humanImageChoice, botImageChoice, finalMessage) {
var imagesDatabase = {
'rock': document.getElementById('rock').src,
'paper': document.getElementById('paper').src,
'scissors': document.getElementById('scissors').src
}
document.getElementById('rock').remove();
document.getElementById('paper').remove();
document.getElementById('scissors').remove();
var humanDiv = document.createElement('div');
var botDiv = document.createElement('div');
var messageDiv = document.createElement('div');
humanDiv.innerHTML = "<img src='" + imagesDatabase[humanImageChoice] + "' height=150 width=150 style='box-shadow: 0px 10px 50px rgba(37,50,233,1);'>"
botDiv.innerHTML = "<img src='" + imagesDatabase[botImageChoice] + "' height=150 width=150 style='box-shadow: 0px 10px 50px rgba(3243,38,24,1);'>"
messageDiv.innerHTML = "<h1 style='color: " + finalMessage['color'] + "; font-size: 60px;padding:30px; '>" + finalMessage['message'] + "</h1>"
document.getElementById('flex-box-rps-div').appendChild(humanDiv);
document.getElementById('flex-box-rps-div').appendChild(messageDiv);
document.getElementById('flex-box-rps-div').appendChild(botDiv);
}
//challenge4
var all_buttons = document.getElementsByTagName('button'); //all button names are saved
var copyAllButtons = [];
console.log(all_buttons);
for (let i = 0; i < all_buttons.length; i++) {
copyAllButtons.push(all_buttons[i].classList[1]);
}
console.log(copyAllButtons); //####Button array is empty####
function buttonColorChange(buttonThingy) {
if (buttonThingy.value === 'red') {
buttonsRed();
} else if (buttonThingy.value === 'green') {
buttonsGreen();
} else if (buttonThingy.value === 'reset') {
buttonsColorReset();
} else if (buttonThingy.value === 'random') {
randomColors();
}
}
function buttonsRed() {
for (let i = 0; i < all_buttons.length; i++) {
all_buttons[i].className = 'btn btn-danger';
}
}
function buttonsGreen() {
for (let i = 0; i < all_buttons.length; i++) {
all_buttons[i].className = 'btn btn-success';
}
}
function buttonsColorReset() { //##function that i am working on##
for (let i = 0; i < all_buttons.length; i++) {
all_buttons[i].classList.remove(all_buttons[i].classList[1]);
all_buttons[i].classList.add(copyAllButtons[i]);
}
}
function randomColors() {
for (let i = 0; i < all_buttons.length; i++) {
var x = Math.floor(Math.random() * 4);
var y = ['btn-primary', 'btn-danger', 'btn-warning', 'btn-success'];
all_buttons[i].className = 'btn ' + y[x];
}
}
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">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="style.css">
<title>challenge game</title>
</head>
<body>
<script src="home.js"></script>
<div class="container-1">
<h2>Challenge 1: Your Age in Days</h2>
<div class="flex-box-container-1">
<div> <button class="btn btn-primary" onclick="ageInDays()">Click Me</button></div>
<div> <button class="btn btn-danger" onclick="reset()">Reset</button></div>
</div>
</div>
<div class="flex-box-container-1">
<div id="flex-box-result">
</div>
</div>
<div class="container-2">
<h2>Challenge 2: Cat Generator</h2>
<button class="btn btn-success" id="cat-generator" onClick="generateCat()">Generate Cat</button>
<div class="flex-box-container-2" id="flex-cat-gen">
</div>
</div>
<div class="container-3">
<h2>Challenge 3:Rock,Paper,Scissors</h2>
<div class="flex-box-rps" id="flex-box-rps-div">
<img id="rock" src="https://cdn.drawception.com/images/panels/2017/2-4/wqmCPbxybn-4.png" alt=""
onClick="rpsGame(this)" width="250" height="250">
<img id="paper" src="https://sc04.alicdn.com/kf/UTB8apntp0nJXKJkSaiyq6AhwXXaR.jpg" alt="" onClick="rpsGame(this)"
width="250" height="250">
<img id="scissors" src="https://www.collinsdictionary.com/images/full/scissors_100136453.jpg" alt=""
onClick="rpsGame(this)" width="250" height="250">
</div>
</div>
<div class="container-4">
<h2 id="change-my-color">Challenge 4:Change the color of all buttons</h2>
<div class="flex-box-pick-color">
<form action="">
<select name="backdrop" id="background" onChange="buttonColorChange(this)">
<option value="random">Random</option>
<option value="red">Red</option>
<option value="green">Green</option>
<option value="reset">Reset</option>
</select>
</form>
<button class="btn btn-primary">Wee!</button>
<button class="btn btn-danger">Yahoo!</button>
<button class="btn btn-warning">Google!</button>
<button class="btn btn-success">Facebook!</button>
</div>
</div>
</body>
</html>
CSS:
.container-1, .container-2 , .container-3 ,.container-4{
border: 1px solid blue;
width:75%;
margin: 0 auto;
text-align: center;
}
.flex-box-container-1, .flex-box-container-2,.flex-box-rps,.flex-box-pick-color{
display:flex;
border:1px solid purple;
padding: 10px;
flex-wrap:wrap;
flex-direction: row;
justify-content: space-around;
}
.flex-box-container-1 div{
display:flex;
padding: 10px;
border: 1 px solid black;
align-items: center;
}
.flex-box-container-2 img{
margin:10px;
box-shadow: 0px 10px 50px rgba(0,0,0,0.7);
}
.flex-box-rps img:hover{
box-shadow: 0px 10px 50px rgba(37,50,233,1);
}
Map button properties to a new array for later use, a minimal reproducable example.
// map button.btn properties to strings with id and class list
const all_buttons = [...document.querySelectorAll('button.btn')]
.map(b => `button#${b.id}, class: ${[...b.classList].join(', ')}`);
console.log(all_buttons);
// so ...
// save original classNames
const initialButtonClasses = [...document.querySelectorAll('button')]
.map(bttn => [...bttn.classList]);
// replacement classes
const green = [`btn`, `green`];
document.addEventListener(`click`, handle);
function handle(evt) {
if (evt.target.dataset.reset) {
return document.querySelectorAll('button.btn')
.forEach((btn, i) => {
btn.classList.remove(...btn.classList);
btn.classList.add(...initialButtonClasses[i]);
});
}
if (evt.target.dataset.green) {
return document.querySelectorAll('button.btn')
.forEach((btn, i) => {
btn.classList.remove(...btn.classList);
btn.classList.add(...green);
});
}
}
.green {
color: green;
}
<button id="a" class="btn z">bttnA</button>
<button id="b" class="btn y">bttnB</button>
<button id="c" class="btn x">bttnC</button>
<button data-green="1">all green</button>
<button data-reset="1">reset</button>
After searching for a long time, I found that I made a mistake in index.html, script tag should be put at the end of the body.

Simple JS carousel need advice

I am trying to create a simple carousel with JavaScript, I am having one issue, how can I display the slides, based on the startingPosition value?
const items = document.getElementsByClassName("carousel__item")
let startingPosition = 0;
let totalItems = items.length;
const prevButton = document.querySelector(".prev")
const nextButton = document.querySelector(".next")
prevButton.addEventListener("click", () => {
if(startingPosition == 0) return;
startingPosition--;
}
);
nextButton.addEventListener("click", () => {
startingPosition++;
if(startingPosition == totalItems) {
startingPosition = 0;
}
}
);
.carousel {
max-width: 400px;
margin: 0 auto;
}
.carousel__item > img {
width: 100%;
}
<div class="carousel">
<div class="carousel__item">
<img src="https://www.greenqueen.com.hk/wp-content/uploads/2021/06/WEF-Investments-In-Nature-Based-Solutions-Have-To-Triple-By-2030-To-Address-Climate-Change-Biodiversity-Loss.jpg" />
</div>
<div class="carousel__item">
<img src="https://tr-images.condecdn.net/image/LDM0pgM40l1/crop/2040/f/gettyimages-1146431497.jpg" />
</div>
</div>
<button class="prev">
Prev
</button>
<button class="next">
Next
</button>
You need to write function to show the active image based on startingPosition.
showSlides does the same thing. It goes through all carousel__item and hide all of them and show only the picture in startingPosition position.
const items = document.getElementsByClassName("carousel__item")
let startingPosition = 0;
let totalItems = items.length;
showSlides(startingPosition);
const prevButton = document.querySelector(".prev")
const nextButton = document.querySelector(".next")
function showSlides(n) {
var i;
var slides = document.getElementsByClassName("carousel__item");
if (n > slides.length) { startingPosition = 1 }
if (n < 1) { startingPosition = slides.length }
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
slides[startingPosition - 1].style.display = "block";
}
prevButton.addEventListener("click", () => {
if (startingPosition == 0) return;
startingPosition--;
showSlides(startingPosition);
}
);
nextButton.addEventListener("click", () => {
startingPosition++;
if (startingPosition == totalItems) {
startingPosition = 0;
}
showSlides(startingPosition);
});
.carousel {
max-width: 400px;
margin: 0 auto;
}
.carousel__item > img {
width: 250px;
height: 150px;
}
<div class="carousel">
<div class="carousel__item">
<img src="https://www.w3schools.com/howto/img_lights_wide.jpg" />
</div>
<div class="carousel__item">
<img src="https://tr-images.condecdn.net/image/LDM0pgM40l1/crop/2040/f/gettyimages-1146431497.jpg" />
</div>
</div>
<button class="prev">
Prev
</button>
<button class="next">
Next
</button>

How to retrieve the data from database according to the button value

I have a page which is showing food details.
The food has two categories. Those are Maincat, subcat.
Maincat Subcat
Indian Food north indian food
Indian Food south indian food
Italian Food Rolex Watch premier
Italian Food south italian food
Rolex Watch premier Rolex Watch
So through this page, when user click maincat value (this is a button) it should show all its particular subcat values .
for example
if user click indian food, then all sub categories of indian food should be show.
i have refer this link enter link description here
my code is
<div id="up"><button class="previous round ar">⇪</button></div>
<div style="float: right; display: inline; padding-right: 100px;">
<?php while($row2 = mysqli_fetch_array($result4)){ ?>
<div class="filterDiv <?php echo $row2[mainName]; ?>"> <?php echo "$row2[name]"; ?> <img style="width: 50px; height: 50px;" src="maincat/<?php echo $row2['image']; ?>"> </div>
<?php } ?>
</div>
<div id="parent" >
<div id="myBtnContainer" style="display: inline;">
<?php while($row1 = mysqli_fetch_array($result3)){ ?>
<div class="child">
<button class="btn draw-border" onclick="filterSelection('<?php echo $row1[3]; ?>')"><?php echo "$row1[0]"; ?><img style="width: 50px; height: 50px;" src="maincat/<?php echo $row1[1]; ?>"></button>
<div class="divider"/>
</div>
<?php } ?>
</div>
</div>
<div id="down"><button class="next round ar" style="float: left;">⇩</button></div>
<div class="clearfix">
</div>
</div>
my script
<script>
function filterSelection(c) {
var x, i;
x = document.getElementsByClassName("filterDiv");
if (c == "all") c = "";
for (i = 0; i < x.length; i++) {
w3RemoveClass(x[i], "show");
if (x[i].className.indexOf(c) > -1) w3AddClass(x[i], "show");
}
}
function w3AddClass(element, name) {
var i, arr1, arr2;
arr1 = element.className.split(" ");
arr2 = name.split(" ");
for (i = 0; i < arr2.length; i++) {
if (arr1.indexOf(arr2[i]) == -1) {element.className += " " + arr2[i];}
}
}
function w3RemoveClass(element, name) {
var i, arr1, arr2;
arr1 = element.className.split(" ");
arr2 = name.split(" ");
for (i = 0; i < arr2.length; i++) {
while (arr1.indexOf(arr2[i]) > -1) {
arr1.splice(arr1.indexOf(arr2[i]), 1);
}
}
element.className = arr1.join(" ");
}
// Add active class to the current button (highlight it)
var btnContainer = document.getElementById("myBtnContainer");
var btns = btnContainer.getElementsByClassName("btn");
for (var i = 0; i < btns.length; i++) {
btns[i].addEventListener("click", function(){
var current = document.getElementsByClassName("active");
current[0].className = current[0].className.replace(" active", "");
this.className += " active";
});
}
</script>
my mysql query
$sql3="SELECT a.name,a.image,b.image,b.name FROM food_main_cat a , food_sub_cat b WHERE b.mainName=a.name GROUP BY(a.name) ";
$result3=mysqli_query($cn,$sql3);
$sql4="SELECT * FROM `food_sub_cat`";
$result4=mysqli_query($cn,$sql4);
my problem is subcat are not showing.
Here's my take on it. I've tried to simplify it. I've taken the example you linked to.
Instead of working with classes I've used data attributes.
doFilter( 'all' );
// Add active class to the current button (highlight it)
var btns = document.getElementsByClassName("btn");
for ( btn of btns ) {
btn.addEventListener("click", function(){
let current = document.getElementsByClassName("active");
current[0].classList.remove("active");
this.className += " active";
let target = this.getAttribute('data-target');
doFilter( target );
});
}
function doFilter( target ) {
let filterDivs = document.getElementsByClassName('filterDiv');
for( fDiv of filterDivs ){
let currentDiv = fDiv;
if( target == 'all' ){
currentDiv.className += ' show';
} else {
let filterTargets = currentDiv.getAttribute('data-target').split(' ');
currentDiv.classList.remove('show');
for( filterTarget of filterTargets ){
if( filterTarget == target ){
currentDiv.className += ' show';
}
}
}
}
}
.filterDiv {
float: left;
background-color: #2196F3;
color: #ffffff;
width: 100px;
line-height: 100px;
text-align: center;
margin: 2px;
display: none;
}
.show {
display: block;
}
.container {
margin-top: 20px;
overflow: hidden;
}
/* Style the buttons */
.btn {
border: none;
outline: none;
padding: 12px 16px;
background-color: #f1f1f1;
cursor: pointer;
}
.btn:hover {
background-color: #ddd;
}
.btn.active {
background-color: #666;
color: white;
}
<h2>Filter DIV Elements</h2>
<div id="myBtnContainer">
<button class="btn active" data-target="all"> Show all</button>
<button class="btn" data-target="cars"> Cars</button>
<button class="btn" data-target="animals"> Animals</button>
<button class="btn" data-target="fruits"> Fruits</button>
<button class="btn" data-target="colors"> Colors</button>
</div>
<div class="container">
<div class="filterDiv" data-target="cars">BMW</div>
<div class="filterDiv" data-target="colors fruits">Orange</div>
<div class="filterDiv" data-target="cars">Volvo</div>
<div class="filterDiv" data-target="colors">Red</div>
<div class="filterDiv" data-target="cars animals">Mustang</div>
<div class="filterDiv" data-target="colors">Blue</div>
<div class="filterDiv" data-target="animals">Cat</div>
<div class="filterDiv" data-target="animals">Dog</div>
<div class="filterDiv" data-target="fruits">Melon</div>
<div class="filterDiv" data-target="fruits animals">Kiwi</div>
<div class="filterDiv" data-target="fruits">Banana</div>
<div class="filterDiv" data-target="fruits">Lemon</div>
<div class="filterDiv" data-target="animals">Cow</div>
</div>

Values not getting saved onsubmit of form using local storage

I want to capture 2 values (product name and energy consumption)from a form and store it using local Storage.
OnClick I want to display the stored values on the side of the form.
What is working
local storage is getting set.
Issues (in the commented function compareSetup)
1) My guess is I am not getting the selected product nor the energy values from the form itself.
2) wrote the display logic but getting error on that line
Uncaught SyntaxError: Unexpected identifier.
I tried 2 different ways. I am newbie hence trying different syntax
3) Resources tab in Chrome shows
callAnnual as undefined
callProduct as 0
4) alerts inside function did not work
I missing something. either logically or syntaxwise or both.
Can some one guide me please. Thanks for your time.
var wattage = {
'Artic King AEB': 100,
'Artic King ATMA': 200,
'Avanti Compact': 300,
'Bosch SS': 400,
'Bosch - SHXUC': 100,
'Asko DS': 200,
'Blomberg': 300,
'Amana': 400
};
var annualEnergy = 0;
var dailyEnergyConsumed = 0;
function configureDropDownLists(category, products) {
var refrigerators = new Array('Artic King AEB', 'Artic King ATMA', 'Avanti Compact', 'Bosch SS');
var dishWasher = new Array('Bosch - SHXUC', 'Asko DS', 'Blomberg', 'Amana');
//var wattage = {'Artic King AEB':100,'Artic King ATMA':200,'Avanti Compact':300;'Bosch SS':400,'Bosch - SHXUC':100;'Asko DS':200;'Blomberg':300;'Amana':400}
switch (category.value) {
case 'refrigerators':
products.options.length = 0;
for (i = 0; i < refrigerators.length; i++) {
createOption(products, refrigerators[i], refrigerators[i]);
}
break;
case 'dishWasher':
products.options.length = 0;
for (i = 0; i < dishWasher.length; i++) {
createOption(products, dishWasher[i], dishWasher[i]);
}
break;
default:
products.options.length = 0;
break;
}
}
function createOption(ddl, text, value) {
var opt = document.createElement('option');
opt.value = value;
opt.text = text;
ddl.options.add(opt);
}
function configureProductDropDownLists(product) {
document.getElementById('wattage').innerText = wattage[product.value];
}
function setConsumption(hrs) {
setConsumption();
}
dailyEnergyConsumption = function(hrs) {
dailyEnergyConsumed = 0;
dailyEnergyConsumed = parseFloat(hrs * parseInt(document.getElementById('wattage').innerText) / 1000).toFixed(2);
document.getElementById('dailyEnergyConsumptionVal').innerText = dailyEnergyConsumed + " kWh";
}
annualEnergyConsumption = function(days) {
annualEnergy = 0;
var allYear = document.getElementById('allYear');
var halfYear = document.getElementById('halfYear');
var threeMonths = document.getElementById('threeMonths');
var oneMonth = document.getElementById('oneMonth');
if (allYear || days != 365) {
annualEnergy = parseFloat(dailyEnergyConsumed * parseInt(days)).toFixed(2);
document.getElementById('annualEnergyConsumption').innerText = annualEnergy + " kWh";
} else if (days == 182 && !halfYear) {
annualEnergy = parseFloat(dailyEnergyConsumed * parseInt(days)).toFixed(2);
document.getElementById('annualEnergyConsumption').innerText = annualEnergy + " kWh";
} else if (days == 90 && !threeMonths) {
annualEnergy = parseFloat(dailyEnergyConsumed * parseInt(days)).toFixed(2);
document.getElementById('annualEnergyConsumption').innerText = annualEnergy + " kWh";
} else if (days == 30 && !oneMonth) {
annualEnergy = parseFloat(dailyEnergyConsumed * parseInt(days)).toFixed(2);
document.getElementById('annualEnergyConsumption').innerText = annualEnergy + " kWh";
}
}
/*
function compareSetup(){
// I am trying to set the local storage for 2 things : selected [product name and Annual Energy Consumption]. End goal is to use them inorder to plot a chart
//initialize the selected product and annual consumption by calling their latest values on submit
var submittedProduct = document.getElementById("products").options.selectedIndex;
var submittedAnnualEnergyConsumption = document.getElementById("annualEnergyConsumption").value;
//alert(submittedProduct);
//setting the local storage with a key and variable name which was defined above
localStorage.setItem("callProduct", submittedProduct);
localStorage.setItem("callAnnual", submittedAnnualEnergyConsumption);
//get Item with a key and display
var displayName = localStorage.getItem("callProduct");
//alert(callProduct);
displayName = document.getElementById("displayName");
var displayAnnual = document.getElementById("displayAnnual").innerHTML = localStorage.getItem parseInt(("callAnnual"));
// return false as I dont want the form to submit
return false;
}
*/
$(document).ready(function() {
$("#h1").click(function() {
$("#onesSelected").show();
$("#threeSelected").hide();
$("#sixSelected").hide();
$("#twentyFourSelected").hide();
});
$("#h3").click(function() {
$("#threeSelected").show();
$("#onesSelected").hide();
$("#sixSelected").hide();
$("#twentyFourSelected").hide();
});
$("#h6").click(function() {
$("#sixSelected").show();
$("#onesSelected").hide();
$("#threeSelected").hide();
$("#twentyFourSelected").hide();
});
$("#h24").click(function() {
$("#twentyFourSelected").show();
$("#onesSelected").hide();
$("#threeSelected").hide();
$("#sixSelected").hide();
});
});
/*
annualCost = function() {
// utility rate currently is hard coded but this will come from the database and shall be inputted by user once. Utility Rate does not change that often
var utilityRate = 0.11;
var button = document.getElementById('annualCost');
var annualCost = parseFloat( annualEnergy * utilityRate).toFixed(2);
document.getElementById('annualCostOperation').innerText= "$" + annualCost ;
}
*/
#leftColumn {
width: 600px;
float: left;
}
.placeholderText {
font: bold 12px/30px Georgia, serif;
}
body {
padding-left: 45px;
}
#annualEnergyConsumption {
font: bold 25px arial, sans-serif;
color: #00ff00;
}
#dailyEnergyConsumptionVal {
font: bold 25px arial, sans-serif;
color: #00ff00;
}
#annualCostOperation {
font: bold 40px arial, sans-serif;
color: #00ff00;
}
.dailyButInline {
display: inline;
}
#wattage {
position: absolute;
left: 160px;
top: 130px;
font: bold 25px arial, sans-serif;
color: #00ff00;
}
/* mouse over link */
button:hover {
background-color: #b6b6b6;
}
#onesSelected {
position: absolute;
left: 53px;
top: 246px;
background-color: #00ff00;
display: none;
width: 99px;
height: 5px;
}
#threeSelected {
position: absolute;
left: 156px;
top: 246px;
background-color: #00ff00;
display: none;
width: 99px;
height: 5px;
}
#sixSelected {
position: absolute;
left: 259px;
top: 246px;
background-color: #00ff00;
display: none;
width: 99px;
height: 5px;
}
#twentyFourSelected {
position: absolute;
left: 362px;
top: 246px;
background-color: #00ff00;
display: none;
width: 113px;
height: 5px;
}
<h2>Annual Energy Consumption and Cost Calculator</h2>
<form method="post" onSubmit="return compareSetup()">
<div id="leftColumn">
<div>
<span class="placeholderText">Choose Category</span>
<span>
<select id="ddl" onchange="configureDropDownLists(this,document.getElementById('products'))">
<option value="">Select a Category</option>
<option value="refrigerators">Refrigerators</option>
<option value="dishWasher">DishWasher</option>
</select>
</span>
</br>
<span class="placeholderText">Select a Product</span>
<span>
<select id="products" onchange="configureProductDropDownLists(this)">
<option selected>--------------------------</option>
</select>
</span>
</div>
<div>
<span class="placeholderText">Wattage</span>
<span id="wattage">---</span>
</br>
</br>
</div>
<div id="buttonBoundary">
<div class="placeholderText">Estimated Daily Use</div>
<div class="dailyButInline">
<button type="button" id="h1" onclick="dailyEnergyConsumption(1)">Not a Lot</br>1 hour per day</button>
</div>
<div class="dailyButInline">
<button type="button" id="h3" onclick="dailyEnergyConsumption(3)">Average</br>3 hour per day</button>
</div>
<div class="dailyButInline">
<button type="button" id="h6" onclick="dailyEnergyConsumption(6)">A Lot</br>6 hour per day</button>
</div>
<div class="dailyButInline">
<button type="button" id="h24" onclick="dailyEnergyConsumption(24)">Always On</br>24 hours per day</button>
</div>
<div id="onesSelected"></div>
<div id="threeSelected"></div>
<div id="sixSelected"></div>
<div id="twentyFourSelected"></div>
</br>
</br>
</div>
<div>
<span class="placeholderText">Daily Energy Consumption</span>
</br>
<div id="dailyEnergyConsumptionVal">---</div>
</br>
</div>
<div>
<span class="placeholderText">Estimated Yearly Use</span>
</br>
<input type="radio" name="usageRadio" value="AllYear" id="allYear" onclick="annualEnergyConsumption(365)" />
<label for="allYear">All year</label>
<input type="radio" name="usageRadio" value="halfYear" id="halfYear" onclick="annualEnergyConsumption(182)" />
<label for="halfYear">6 Months</label>
<input type="radio" name="usageRadio" value="threeMonths" id="threeMonths" onclick="annualEnergyConsumption(90)" />
<label for="threeMonths">3 Months</label>
<input type="radio" name="usageRadio" value="oneMonth" id="oneMonth" onclick="annualEnergyConsumption(30)" />
<label for="oneMonth">1 Month</label>
<!-- <div id="daysUsed"><input type="number" id="hour" maxlength="2" min="1" onchange="annualEnergyConsumption(this.value)"></br> -->
</div>
</br>
<div>
<span class="placeholderText">Energy Consumption</span>
</br>
<div id="annualEnergyConsumption">---</div>
</br>
</div>
<input type="submit" value="Save Product" />
</div>
<div id="right">
<div id="displayName">Selected Product 1</div>
<div id="displayAnnual">Selected Product1's Annual Consumption</div>
</div>
<!--
<div id="right">
</form>
<div>
<span class="placeholderText">Enter your Utility Rate per Kw/h</span></br>
<span><input type="number" id="utilityRate" /></span>
</br></br>
</div>
<div>
<span class="placeholderText"><button id="annualCost" onclick='annualCost()'>Annual Cost to Operate</button></span></br>
<span id="annualCostOperation" /></span>
</div>
</div>
-->
</form>
Your scope access of '$' as undefined should be a dead give away as to why the remainder of the code is not working. Once you have called the '$' bit of code within the proper scope it will work.

Categories