Creating an html form and output things based off that data - javascript

I'm relatively new to HTML and I want to create a form so that the user can get a customized output based on their answers. I have a basic form with button inputs, with multiple tabs of buttons. Is there some way for me to collect the data that the user selects by pressing multiple buttons, and assign it to a js variable? This is the code I have so far.
<!DOCTYPE HTML>
<html>
<head>
</head>
<style>
/* Hide all steps by default: */
.tab {
display: none;
}
#myButton {
padding: 0;
border: none;
background: none;
font-family: monospace;
font-size: 25px;
margin-right: 2%;
transition: margin-left 1s;
}
#myButton:hover {
color: rgb(77, 77, 77);
padding-left: 1%;
}
#main {
padding-bottom: 25vh;
padding-top: 25vh;
padding-left: 5%;
padding-right: 5%;
}
/* Header */
#heade {
position: fixed;
top: 0;
left: 0;
width: 100%;
background: #0F1116;
color: #fff;
padding: 3.25em 1.5em 1.5em 1.5em;
z-index: 100;
}
header {
padding-bottom: 30px;
margin-top: -3px;
padding-right: 80%;
}
</style>
<body>
<form id="regForm" style="text-align: center;" method="GET">
<!-- One "tab" for each step in the form: -->
<div class="tab">
<input onmousedown="myFunction()" name="qty" type="button" value="3" onclick="nextPrev(1)" id="myButton">
</div>
<div class="tab">
<ul style="list-style-type:none;">
<li><input name="qty" type="button" value="3" onclick="nextPrev(1)" id="myButton"></li>
<li><input type="button" name=parameter value="Click me" onclick="nextPrev(1)" id="myButton"></li>
<li><input type="button" value="Click me" onclick="nextPrev(1)" id="myButton"></li>
</ul>
</div>
<div class="tab">
<ul style="list-style-type:none;">
<li><input name="qty" type="button" value="3" onclick="nextPrev(1)" id="myButton"></li>
<li><input type="button" value="Click me" onclick="nextPrev(1)" id="myButton"></li>
</ul>
</div>
<div class="tab">
<ul style="list-style-type:none;">
<li><input name="qty" type="button" value="3" onclick="nextPrev(1)" id="myButton" class="ug"></li>
<li><input type="submit" value="Click me" onclick="nextPrev(1)" id="myButton" class="ug"></li>
</ul>
</div>
<div style="overflow:auto;"></div>
<div style="text-align:center;">
<!-- Circles which indicates the steps of the form: -->
<span class="step"></span>
<span class="step"></span>
<span class="step"></span>
<span class="step"></span>
</div>
</div>
</form>
</body>
<script>
var currentTab = 0; // Current tab is set to be the first tab (0)
showTab(currentTab); // Display the current tab
function showTab(n) {
// This function will display the specified tab of the form...
var x = document.getElementsByClassName("tab");
x[n].style.display = "block";
//... and fix the Previous/Next buttons:
if (n == 0) {
document.getElementById("prevBtn").style.display = "none";
} else {
document.getElementById("prevBtn").style.display = "inline";
}
if (n == (x.length - 1)) {
document.getElementById("nextBtn").innerHTML = "Submit";
} else {
document.getElementById("nextBtn").innerHTML = "Next";
}
//... and run a function that will display the correct step indicator:
fixStepIndicator(n)
}
function nextPrev(n) {
// This function will figure out which tab to display
var x = document.getElementsByClassName("tab");
// Exit the function if any field in the current tab is invalid:
if (n == 1 && !validateForm()) return false;
// Hide the current tab:
x[currentTab].style.display = "none";
// Increase or decrease the current tab by 1:
currentTab = currentTab + n;
// if you have reached the end of the form...
if (currentTab >= x.length) {
// ... the form gets submitted:
document.getElementById("regForm").submit();
return false;
}
// Otherwise, display the correct tab:
showTab(currentTab);
}
function validateForm() {
// This function deals with validation of the form fields
var x, y, i, valid = true;
x = document.getElementsByClassName("tab");
y = x[currentTab].getElementsByTagName("input");
// A loop that checks every input field in the current tab:
for (i = 0; i < y.length; i++) {
// If a field is empty...
if (y[i].value == "") {
// add an "invalid" class to the field:
y[i].className += " invalid";
// and set the current valid status to false
valid = false;
}
}
// If the valid status is true, mark the step as finished and valid:
if (valid) {
document.getElementsByClassName("step")[currentTab].className += " finish";
}
return valid; // return the valid status
}
</script>
</html>
There may be some extra code in there as this is part of a larger webpage.

Related

Show child elements if parent is visible

I'm trying to have my form show child elements if the parent is visible and I keep getting an "undefined" error with my child element, even though I have it defined. I'm trying to have set this up where:
Q1: Checked responses will show parent elements (divs).
Q2: Depending on this response, it'll show child elements (divs).
Is there a way to do this?
//Next Tab
function next() {
var formTabOne = document.getElementById("stepOne");
formTabOne.classList.add("formTrans");
formTabOne.addEventListener("transitionend", function({
target
}) {
if (target === formTabOne) {
target.classList.add("hidden");
target.classList.remove("formTrans");
document.getElementById("stepTwo").classList.remove("hidden");
}
})
}
//Prev Tab
function prev() {
var formTabTwo = document.getElementById("stepTwo");
formTabTwo.classList.add("formTrans");
formTabTwo.addEventListener("transitionend", function({
target
}) {
if (target === formTabTwo) {
target.classList.add("hidden");
target.classList.remove("formTrans");
document.getElementById("stepOne").classList.remove("hidden");
}
})
}
function process() {
var form = document.myForm;
var biz = document.getElementById("biz");
var career = document.getElementById("career");
var change = document.getElementById("change");
var eq = document.getElementById("eq");
var empathy = document.getElementById("empathy");
var pm = document.getElementById("pm");
var bizMgr = document.getElementsByClassName("bizMgr");
var bizEE = document.getElementsByClassName("bizEE");
//Q1 - Topics
document.querySelectorAll("#chkTopic input").forEach((el) => {
const contentID = el.id.replace("chk", "").toLowerCase()
document.getElementById(contentID).style.display = el.checked ? "block" : "none";
});
//Q2 - Employee Type
var q2value = "";
for (var i = 0; i < form.q2.length; i++) {
var answer = form.q2[i];
if (answer.checked) {
q2value = answer.value;
}
}
if (q2value == "1") {
if (biz.style.display = "block") {
bizMgr.style.display = "block";
bizEE.style.display = "block";
}
} else {
if (biz.style.display = "block") {
document.getElementsByClassName("bizEE").style.display = "block";
}
}
}
html {
scroll-behavior: smooth;
}
#formWrapper {
background-color: #eaeaea;
padding: 20px;
margin-bottom: 40px;
min-height: 300px;
}
#myForm {
width: 70%;
min-height: 280px;
margin: 0 auto;
padding: 20px;
background-color: #fff;
border: 1px solid #dedede;
box-sizing: border-box;
}
.formStep {
opacity: 1;
background: #fff;
}
.formTrans {
visibility: hidden;
opacity: 0;
transition: visibility 0s 200ms, opacity 200ms linear;
}
.hidden {
display: none;
}
#biz, #career, #change, #eq, #empathy, #pm, #pd {
display: none;
width: 100%;
min-height: 200px;
box-sizing: border-box;
margin-bottom: 30px;
border: 1px solid #000;
}
.bizMgr, .bizEE, .careerMgr, .careerEE, .changeMgr, .changeEE, .eqMgr, .eqEE, .empathyMgr, .empathyEE, .pmMgr, .pmEE, .pdMgr, .pdEE {
display: none;
}
<form name="myForm" id="myForm">
<input type="button" value="Skip This" onclick="formSkip();">
<br><br>
<!--Step 1-->
<div id="stepOne" class="formStep">
<b>Select the topic(s) you're interested in:</b><br>
<div id="chkTopic">
<input id="chkBiz" type="checkbox" value="1"><label for="chkBiz">Business Structure/Acumen</label><br>
<input id="chkCareer" type="checkbox" value="2"><label for="chkCareer">Career Development</label><br>
<input id="chkChange" type="checkbox" value="3"><label for="chkChange">Change</label><br>
<input id="chkEQ" type="checkbox" value="4"><label for="chkEQ">Emotional Intelligence</label><br>
<input id="chkEmpathy" type="checkbox" value="5"><label for="chkEmpathy">Empathy</label><br>
<input id="chkPM" type="checkbox" value="6"><label for="chkPM">Performance Management</label><br>
</div>
<br>
<button type="button" id="btnStepOne" onclick="next();">Next</button>
</div>
<!--Step 2-->
<div id="stepTwo" class="formStep hidden">
<b>Are you a people leader?</b><br>
<input type="radio" name="q2" value="0">No<br>
<input type="radio" name="q2" value="1">Yes<br>
<br>
<button type="button" id="btnStepTwo" onclick="prev();">Previous</button>
<input type="button" value="Show Results" onclick="process();">
<input type="reset" value="Start Over" onclick="formReset();">
</div>
</form>
<div id="results">
<div id="biz">
Business Structure/Acumen
<div class="bizMgr">Manager Content</div>
<div class="bizEE">Employee Content</div>
</div>
<div id="career">
Career Development
<div class="careerMgr">Manager Content</div>
<div class="careerEE">Employee Content</div>
</div>
<div id="change">
Change
<div class="changeMgr">Manager Content</div>
<div class="changeEE">Employee Content</div>
</div>
<div id="eq">
Emotional Intelligence
<div class="eqMgr">Manager Content</div>
<div class="eqEE">Employee Content</div>
</div>
<div id="empathy">
Empathy
<div class="empathyMgr">Manager Content</div>
<div class="empathyEE">Employee Content</div>
</div>
<div id="pm">
Performance Management
<div class="pmMgr">Manager Content</div>
<div class="pmEE">Employee Content</div>
</div>
</div>
.getElementsByClassName returns a collection, bizMgr and bizEE are both collections. You have to iterate the collections and set each element to style.display = 'block'. You can't just call xxx.style.display on a javascript collection. You would want to change your code like the following:
if (q2value == "1") {
if (biz.style.display = "block") {
//bizMgr.style.display = "block"; -NO
//bizEE.style.display = "block"; -NO
for(let i = 0; i < bizMgr.length; i++){
bizMgr[i].style.display = "block";
}
for(let j = 0; j < bizEE.length; j++){
bizEE[j].style.display = "block";
}
}
} else {
if (biz.style.display = "block") {
//document.getElementsByClassName("bizEE").style.display = "block"; -NO
for(let j = 0; j < bizEE.length; j++){
bizEE[j].style.display = "block";
}
}
}

if statement check active class when button is clicked

Trying to make an if statement in JS that when one of the top 3 buttons changes, it checks which of the bottom 2 has the "active" class, and visa versa.
So when I click 30g it will check if option a or option b is active, and then change the price accordingly.
Any help would be greatly appreciated as I'm kind of a noob.
The problem is there are 2 rows of buttons (one to select the weight, and one to select option a or b). I know how it would work, I just don't know the syntax, this is what I want to happen but it's not coded right.
//this is shitty code of what I mean, but I don't know how to code in JS
if(button30g.isclicked && buttonOptionA.ContainsClass.Active)
{ Price=1.00; }
else if(button30g.isClicked && buttonOptionB.ContainsClass.Active)
{ Price=2.00; }
if(button70g.isclicked && buttonOptionA.ContainsClass.Active)
{ Price=3.50; }
else if(button70g.isClicked && buttonOptionB.ContainsClass.Active)
{ Price=4.00; }
if(button70g.isclicked && buttonOptionA.ContainsClass.Active)
{ Price=3.50; }
else if(button70g.isClicked && buttonOptionB.ContainsClass.Active)
{ Price=4.00; }
<!DOCTYPE html>
<html lang="en">
<head>
<style>
ul.nav a{
border: 2px solid #E1E8EE;
border-radius: 6px;
padding: 13px 20px;
font-size: 14px;
color: #5E6977;
background-color: #fff;
cursor: pointer;
transition: all .5s;
display: inline-block;
vertical-align: middle;
}
.activeBtn { color:grey; font-weight:1000; border: 2px solid grey; border-radius: 6px; }
</style>
</head>
<body>
<ul class="nav">
<li id="30" data-price="bird" onclick="myFunction()" class="activeBtn"><a>30g</a></li>
<li id="70" onclick="myFunction()"><a>70g</a></li>
<li id="90" onclick="myFunction()"><a>90g</a></li>
</ul>
<ul class="nav">
<li id="no" class="activeBtn"><a>option a</a></li>
<li id="yes"><a>option b</a></li>
</ul>
<br>
<div class="product-price">
<span id="price">148$</span>
</div>
</body>
<footer>
<script>
$(function() {
$( 'ul.nav li' ).on( 'click', function() {
$( this ).parent().find( 'li.activeBtn' ).removeClass( 'activeBtn' );
$( this ).addClass( 'activeBtn' );
});
});
</script>
<script>
function myFunction() {
const element = document.getElementById("30");
const element2 = document.getElementById("no");
const pricetag = document.getElementById("price");
if(((element.classList.contains("activeBtn"))==true)&&((element2.classList.contains("activeBtn"))==true))
{
pricetag.innerHTML = €1,00;
}
</script>
</footer>
</html>
The work that you want I have done it separately so check this out. This code works according to the option "yes" or "no" and shows the price.
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.radioStyle{
border-color: blue;
border-width: thin;
border-style: solid;
width: 50%;
}
</style>
</head>
<body>
<div><input type="radio" name="grams" value="30" id = "30" onclick="myFunction()"> 30g</div>
<div><input type="radio" name="grams" value="70" id = "70" onclick="myFunction()"> 70g</div>
<div><input type="radio" name="grams" value="90" id = "90" onclick="myFunction()"> 90g </div>
<hr>
<input type="radio" name="option" value="yes" id ="yes" checked onclick="myFunction()"> yes<br>
<input type="radio" name="option" value="no" id = "no" onclick="myFunction()"> no<br>
<br>
<span id = "sp">
0$
</span>
</body>
<footer>
<script>
function setBorder(){
var siblings = document.querySelectorAll('input[name = "grams"]');
siblings.forEach(element => element.parentElement.className="");
var grams = document.querySelector('input[name = "grams"]:checked');
grams.parentElement.className = "radioStyle";
console.log(siblings);
console.log(grams);
}
function myFunction(){
setBorder();
var grams = document.querySelector('input[name = "grams"]:checked').value;
var option = document.querySelector('input[name = "option"]:checked').value;
var rate = 0;
if (option == "yes"){
if (grams == "30")
rate = 1.5;
else if (grams == "70")
rate = 2.5;
else if (grams == "90")
rate = 3.5;
}
else if (option == "no"){
if (grams == "30")
rate = 2;
else if (grams == "70")
rate = 3;
else if (grams == "90")
rate = 4;
}
document.getElementById("sp").innerHTML = rate*grams+"$";
}
</script>
</footer>
</html>

How do I add multiple entries in a list in JavaScript

I have a program for a makeshift task list that I am working on that should allow a user to enter more than one task by separating the tasks with a comma. I am not sure how I would write a portion of code to allow this function. I am trying to also make the lists themselves separate so if a user needed to delete a task, all the tasks would not be deleted too.
"use strict";
var $ = function(id) { return document.getElementById(id); };
var tasks = [];
var displayTaskList = function() {
var list = "";
// if there are no tasks in tasks array, check storage
if (tasks.length === 0) {
// get tasks from storage or empty string if nothing in storage
var storage = localStorage.getItem("tasks") || "";
// if not empty, convert to array and store in global tasks variable
if (storage.length > 0) { tasks = storage.split("|"); }
}
// if there are tasks in array, sort and create tasks string
if (tasks.length > 0) {
tasks.sort();
list = tasks.join("\n");
}
// display tasks string and set focus on task text box
$("task_list").value = list;
$("task").focus();
};
var addToTaskList = function() {
var task = $("task");
if (task.value === "") {
alert("Please enter a task.");
} else {
// add task to array and local storage
tasks.push(task.value);
localStorage.tasks = tasks.join("|");
// clear task text box and re-display tasks
task.value = "";
displayTaskList();
}
};
var clearTaskList = function() {
tasks.length = 0;
localStorage.tasks = "";
$("task_list").value = "";
$("task").focus();
};
window.onload = function() {
$("add_task").onclick = addToTaskList;
$("clear_tasks").onclick = clearTaskList;
displayTaskList();
};
body {
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 100%;
background-color: white;
width: 700px;
margin: 0 auto;
border: 3px solid blue;
padding: 0 2em 1em;
}
h1 {
font-size: 150%;
color: blue;
margin-bottom: .5em;
}
label {
float: left;
width: 8em;
}
input {
width: 22em;
margin-right: 1em;
margin-bottom: 1em;
}
#tasks {
margin-top: 0;
float: right;
}
<!DOCTYPE html>
<html>
<head>
<title>Ch09 Task Manager</title>
<link type="text/css" rel="stylesheet" href="task_list.css">
<script type="text/javascript" src="task_list.js"></script>
</head>
<body>
<main>
<h1>Task Manager</h1>
<div id="tasks">
<span id="name"> </span>Tasks<br>
<textarea id="task_list" rows="8" cols="50"></textarea>
</div>
<label for="task">Task</label><br>
<input type="text" name="task" id="task"><br>
<input type="button" name="add_task" id="add_task" value="Add Task">
<input type="button" name="clear_tasks" id="clear_tasks" value="Clear Tasks"><br>
<input type="button" name="delete_task" id="delete_task" value="Delete Task">
<input type="button" name="toggle_sort" id="toggle_sort" value="Toggle Sort"><br>
<input type="button" name="set_name" id="set_name" value="Set Name">
<input type="button" name="filter_tasks" id="filter_tasks" value="Filter Tasks"><br>
</main>
</body>
</html>
I found a lot of other stuff that needed fixing, so I did (mostly having to do with how you use jQuery). Works for me locally. Snippet runner doesn't want to do some of this stuff - sorry! Don't know about that.
var tasks = [];
var displayTaskList = function() {
var list = "";
if (tasks.length === 0) { // if there are no tasks in tasks array, check storage
var storage = localStorage.getItem("tasks") || ""; // get tasks from storage or empty string if nothing in storage
if (storage.length > 0) {
tasks = storage.split("|");
} // if not empty, convert to array and store in global tasks variable
}
if (tasks.length > 0) { // if there are tasks in array, sort and create tasks string
tasks.sort();
list = tasks.join("\n");
}
$("#task_list").val(list); // display tasks string and set focus on task text box
$("#task").focus();
};
var addToTaskList = function() {
var task = $("#task").val();
console.log(`entering addtotask list with task value = ${task}`);
if (task === "") {
alert("Please enter a task.");
} else {
if (task.indexOf(',') === -1) {
tasks.push(task); // add task to array and local storage
} else {
const split = task.split(','); // 2 lines for readability
split.forEach(atask => {
tasks.push(atask);
});
}
localStorage.tasks = tasks.join("|");
$("#task").val(""); // clear task text box and re-display tasks
displayTaskList();
}
};
var clearTaskList = function() {
tasks.length = 0;
localStorage.tasks = "";
$("#task_list").val("");
$("#task").focus();
};
window.onload = function() {
$("#add_task").on('click', function() {
addToTaskList();
});
$("#clear_tasks").on('click', function() {
clearTaskList();
});
displayTaskList();
};
body {
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 100%;
background-color: white;
width: 800px;
margin: 0 auto;
border: 3px solid blue;
padding: 0 2em 1em;
}
h1 {
font-size: 150%;
color: blue;
margin-bottom: .5em;
}
label {
float: left;
width: 8em;
}
input {
width: 22em;
margin-right: 1em;
margin-bottom: 1em;
}
#tasks {
margin-top: 0;
float: right;
}
<body>
<main>
<h1>Task Manager</h1>
<div id="tasks">
<span id="name"> </span>Tasks<br>
<textarea id="task_list" rows="8" cols="50"></textarea>
</div>
<label for="task">Task</label><br>
<input type="text" name="task" id="task"><br>
<input type="button" name="add_task" id="add_task" value="Add Task">
<input type="button" name="clear_tasks" id="clear_tasks" value="Clear Tasks"><br>
<input type="button" name="delete_task" id="delete_task" value="Delete Task">
<input type="button" name="toggle_sort" id="toggle_sort" value="Toggle Sort"><br>
<input type="button" name="set_name" id="set_name" value="Set Name">
<input type="button" name="filter_tasks" id="filter_tasks" value="Filter Tasks"><br>
</main>
<script src="//code.jquery.com/jquery-3.4.1.min.js"></script>
</body>

Validating function written in javaScript runs only once?

goal : is to validate this form. http://jsbin.com/buwejurexa/1/
Code is below
Show the user all errors at once when he clicks Save Product button and errors at each step also.
What is done:
Wrote a validating function returnVal() which is nested inside another function called displayStorage.
What works :
As the page loads the user clicks the Save Product button and the validating function seems to be working first time. I can see the alert.
The issue starts when:
The user selects the Category and Products and sees Wattage. This
time he decides to click on Save Product. Nothing happens. No
Validations are displayed step by step.
No errors in Console but got a error in JS Bin that (Line 253: Expected a conditional expression and instead saw an assignment.
Line 258: Unreachable 'return' after 'return'.)
My guess :
a) my if and else statement is missing something. I tried calling it from different functions but no luck.
b) The four buttons use Jquery. so I am guessing do I need to call javascript function returnVal() inside Jquery. How do I do that. I did reference the 4 buttons in my validating function.
can some help me get the validations right.
Thanks!!
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 populateProducts(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');
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;
}
populateWattage(products);
}
function createOption(ddl, text, value) {
var opt = document.createElement('option');
opt.value = value;
opt.text = text;
ddl.options.add(opt);
}
function populateWattage(product) {
document.getElementById('wattage').innerText = wattage[product.value];
populateStorage();
}
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";
populateStorage();
};
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";
}
populateStorage();
};
// code that shows which button is clicked. Green div below the 4 buttons
$(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();
});
});
function compareSetup() {
var prodName = localStorage.getItem('productKey');
var energyName = parseInt(localStorage.getItem('energyKey'), 10);
var useName = parseInt(localStorage.getItem('estimatedUse'), 10);
return false;
}
function populateStorage() {
var productBox = document.getElementById("products");
var productName = productBox.options[productBox.selectedIndex].text;
localStorage.setItem('productKey', productName);
localStorage.setItem('energyKey', document.getElementById("annualEnergyConsumption").innerHTML);
//localStorage.setItem.querySelector('input[id="usageRadio"]:checked').value;
//localStorage.setItem('usageRadio' + $(this).attr('id'), JSON.stringify({ checked: this.checked }));
//localStorage.setItem('estimatedUse', document.getElementById("usageRadio"));
// do other things if necessary
}
function displayStorage() {
var displayProduct = document.getElementById("displayName");
var displayAnnual = document.getElementById("displayAnnual");
displayProduct.innerHTML = "Selected Product: " + localStorage.getItem('productKey');
displayProduct.style = "display:inline;";
displayAnnual.innerHTML = "Annual Consumption: " + localStorage.getItem('energyKey');
returnVal();
}
//validation code starts here
function returnVal() {
//initialize the form elements starting from form name , category and product dropdown, daily use buttons and finally the radio buttons
var energyForm = document.getElementsByName("energyForm")[0];
// drop downs
var catDropdown = document.getElementById("dd1");
var prodDropdown = document.getElementById("products");
// call the 4 Daily use button
var notLotButton = document.getElementById("h1");
var averageButton = document.getElementById("h3");
var lotButton = document.getElementById("h6");
var alwaysButton = document.getElementById("h24");
// radio button group
var allYearRadio = document.getElementById("allYear");
var halfYearRadio = document.getElementById("halfYear");
var threeMonthsRadio = document.getElementById("threeMonths");
var oneMonthRadio = document.getElementById("oneMonth");
//
var missingFields = false;
var strFields = "";
if (catDropdown.selectedIndex === 0) {
missingFields = true;
strFields += "Select Category and the related Product \n";
catDropdown.focus();
} else {
return true;
}
if ((!notLotButton.clicked) &&
(!averageButton.clicked) &&
(!lotButton.clicked) &&
(!alwaysButton.clicked)) {
missingFields = true;
strFields += "Select atleast one Estimated Daily Use option \n";
} else {
return true;
}
if ((!allYearRadio.checked) &&
(!halfYearRadio.checked) &&
(!threeMonthsRadio.checked) &&
(!oneMonthRadio.checked)) {
missingFields = true;
strFields += "Select atleast one Estimated Yearly Use option \n";
} else {
return true;
}
if (missingFields = true) {
alert("Please provide the following fields before continuing: \n" + strFields);
}
return false;
return true;
}
function resetForm() {
document.getElementById("resetButton");
document.getElementById("energyForm").reset();
document.getElementById('products').value = "select";
//document.getElementById('select_value').selectedIndex = 3;
}
#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;
}
#store {
cursor: pointer;
}
<h2>Annual Energy Consumption and Cost Calculator</h2>
<form id="energyForm" onSubmit="return compareSetup()" action="" method="post">
<div id="leftColumn">
<div>
<span class="placeholderText">Choose Category</span>
<span>
<select id="dd1" name="dd1" onchange="populateProducts(this,document.getElementById('products'))" required>
<option value="select">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="populateWattage(this)" required>
<option value="select" selected>--------------------------</option>
</select>
</span>
</div>
<div>
<span class="placeholderText">Wattage</span>
<span id="wattage">0</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="365" id="allYear" onclick="annualEnergyConsumption(365)" />
<label for="allYear">All year</label>
<input type="radio" name="usageRadio" value="182" id="halfYear" onclick="annualEnergyConsumption(182)" />
<label for="halfYear">6 Months</label>
<input type="radio" name="usageRadio" value="90" id="threeMonths" onclick="annualEnergyConsumption(90)" />
<label for="threeMonths">3 Months</label>
<input type="radio" name="usageRadio" value="30" 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" onclick="displayStorage()" />
<input type="reset" onclick="resetForm()" id="resetButton" value="Reset" />
</div>
<div id="right">
<div id="displayName">Selected Product:</div>
<div id="displayAnnual">Annual Consumption:</div>
</div>
</form>
In the last statements of your function, there are two mistakes:
if (missingFields = true) { // should be: missingFields == true
alert("Please provide the following fields before continuing: \n" + strFields);
}
return false;
return true; // You already returned false; did you mean to return false inside the if?

Javascript Showing div function

<script language="javascript">
function switchdiv() {
var e = document.getElementById().id;
if(e == 'Streambtn')
document.getElementById('Stream').style.display = "block";
else
document.getElementById('Stream').style.display = "none";
}
</script>
Hello,
Here is my problem. When I click, nothing happen...
I hope you can help me.
Thank you
Edit :
Thank you for your answer zzlalani but it unfortunately does not work.
Here is the final code, hoping you'll help me to find a way to fix the problem.
<div align="center">
<input type="button" class="btn" name="Stream" value="Stream" style="padding: 10px 20px 10px 20px; border: 0px; font-family: Play, sans-serif; font-weight: bold" onClick="switchdiv("Streambtn")"/>
<input type="button" class="btn" name="Youtube" value="Youtube" style="padding: 10px 20px 10px 20px; border: 0px; font-family: Play, sans-serif; font-weight: bold" onClick="switchdiv("Youtubebtn")"/>
<input type="button" class="btn" name="LoL" value="League Of Legends" style="padding: 10px 20px 10px 20px; border: 0px; font-family: Play, sans-serif; font-weight: bold" onClick="switchdiv("LoLbtn")"/>
</div>
<script language="javascript">
function switchdiv(e) {
if(e == 'Streambtn')
document.getElementById('Stream').style.display = "block";
else
document.getElementById('Stream').style.display = "none";
}
if(e == 'Youtubebtn')
document.getElementById('Youtube').style.display = "block";
else
document.getElementById('Youtube').style.display = "none";
}
if(e == 'LoLbtn')
document.getElementById('LoL').style.display = "block";
else
document.getElementById('LoL').style.display = "none";
}
</script>
<div align="center" id="Stream" hidden>
<p>a</p>
</div>
<div align="center" id="Youtube" hidden>
<p>b</p>
</div>
<div align="center" id="LoL" hidden>
<p>c</p>
</div>
Let say you have button that calls switchdiv on click
<input type='button' onClick='switchdiv("Streambtn");' value='Stream!'>
<input type='button' onClick='switchdiv("nonStreambtn");' value='Non Stream!'>
Then it will goes like this
<script language="javascript">
function switchdiv(e) {
if(e == 'Streambtn')
document.getElementById('Stream').style.display = "block";
else
document.getElementById('Stream').style.display = "none";
}
</script>
The problem in you code is you are getting the value of nothing.. check it in this way
var e = document.getElementById().id;
console.log(e);
in the console of the browser you can see that will be either show some weird errors in red

Categories

Resources