Show child elements if parent is visible - javascript

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";
}
}
}

Related

Target every label elements that has the correct data-answer attributs with javascript

I have a HTML code and I want to select each label that has the data-anwser set to "correct", how can I do it with pure Javascript? Here's my HTML
<div class="form-group answer" role="group">
<label data-answer="correct">
<div>Test</div>
</label>
</div>
<div class="form-group answer" role="group">
<label data-answer="incorrect">
<div>Test</div>
</label>
</div>
And here's the begining of what I tried with the JS
<script>
var div = document.getElementsByClassName('answer');
window.onload = (event) => {
for (var i = 0; i < div.length; i++) {
var label = div[i].getElementsByTagName('label');
if (label[i].dataset == 'correct') {
console.log("CORRECTE");
} else {
console.log("INCORECTE");
}
console.log(label[i].dataset);
}
}
</script>
Thank you:)
use query selectors:
const btn = document.getElementById('btn');
btn.addEventListener('click', ev => {
const correctAnswers = document.querySelectorAll('.answer [data-answer="correct"]');
correctAnswers.forEach(el => {
el.classList.toggle('selected');
});
});
.form-group > label {
margin: 0.33em;
padding: 0.33em;
border: 2px solid gray;
background-color: silver;
width: 250px;
display: inline-block;
}
.form-group > label.selected {
background-color: yellow;
border: 2px dotted black;
}
<div class="form-group answer" role="group">
<label data-answer="correct">
<div>Test 1</div>
</label>
</div>
<div class="form-group answer" role="group">
<label data-answer="incorrect">
<div>Test 2</div>
</label>
</div>
<div class="form-group answer" role="group">
<label data-answer="correct">
<div>Test 3</div>
</label>
</div>
<button id="btn">highlight correct answers</button>
Try this
var answersCorrect = document.querySelectorAll("*[data-answer='correct']")
Array.from(answersCorrect).forEach(element => {
console.log(element)
})

Creating an html form and output things based off that data

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.

Only allow the user to select a maximum of three blocks

I have a piece of code that adds an event listener to a number of buttons, when the user clicks a button a class is applied to the button container. How can I restrict this so the user can only select a maximum of three buttons. The code below is working to a point, when you get to three you cannot deselect. Can anyone help me achieve
var blocks = document.querySelectorAll(".block");
var btn = document.querySelectorAll("button");
var total = 0;
for (let i = 0; i < btn.length; i++) {
btn[i].addEventListener("click", function() {
if (total < 3 && blocks[i].classList.contains("active")) {
blocks[i].classList.remove("active");
total--;
} else if (total < 3 && !blocks[i].classList.contains("active")) {
blocks[i].classList.add("active");
total++;
}
});
}
.container{
display:flex;
}
.block{
padding: 50px;
border:1px solid;
max-width:
}
.block.active{
background:grey;
}
<div class="container">
<div class="block">
<button>click</button>
</div>
<div class="block">
<button>click</button>
</div>
<div class="block">
<button>click</button>
</div>
<div class="block">
<button>click</button>
</div>
</div>
this.
You simply need to remove this condition total < 3 && from your first if. The number of selected items is irrelevant if the element is already selected. You just want to de-select it.
var blocks = document.querySelectorAll(".block");
var btn = document.querySelectorAll("button");
var total = 0;
for (let i = 0; i < btn.length; i++) {
btn[i].addEventListener("click", function() {
if (blocks[i].classList.contains("active")) {
blocks[i].classList.remove("active");
total--;
} else if (total < 3 && !blocks[i].classList.contains("active")) {
blocks[i].classList.add("active");
total++;
}
});
}
.container{
display:flex;
}
.block{
padding: 50px;
border:1px solid;
max-width:
}
.block.active{
background:grey;
}
<div class="container">
<div class="block">
<button>click</button>
</div>
<div class="block">
<button>click</button>
</div>
<div class="block">
<button>click</button>
</div>
<div class="block">
<button>click</button>
</div>
</div>

Getting three images to display beside each other

I know this question has been asked a hundred times but I cant seem to find an answer that works for me on any other thread. I am displaying images, and want three of them to be in a row, but they are all just below each other.
//displaying multiple images and delete them
const deleteFiles = [];
$("#file-upload").on("change", function(event) {
const files = event.originalEvent.target.files;
const fragmentElement = document.createDocumentFragment();
const galleryElement = document.querySelector('div.gallery');
if (galleryElement === null) {
return
}
for (let i = 0; i < files.length; i++) {
const file = files[i];
deleteFiles.push(file);
const deleteImg = document.createElement("div");
const deleteimage = document.createElement("img");
const faGlyph = document.createElement('i');
faGlyph.className = 'fas fa-times';
deleteImg.className = 'thumbnail-container';
deleteimage.className = 'thumbnail';
faGlyph.style.display = 'none';
deleteImg.appendChild(deleteimage);
deleteImg.appendChild(faGlyph);
fragmentElement.appendChild(deleteImg);
deleteimage.src = URL.createObjectURL(file);
function toggleGlyph() {
var jqGlyph = $(faGlyph);
if (jqGlyph.is(':visible')) {
jqGlyph.hide();
} else {
jqGlyph.show();
}
}
function deletePic() {
const index = deleteFiles.indexOf(file);
if (index !== -1) {
deleteFiles.splice(index, 1);
}
URL.revokeObjectURL(file);
deleteImg.parentElement.removeChild(deleteImg);
}
$(deleteImg).hover(toggleGlyph, toggleGlyph);
faGlyph.addEventListener('click', deletePic, false);
}
galleryElement.appendChild(fragmentElement);
$('div.gallery').show();
});
.form {
overflow: hidden;
}
/*upload image */
.gallery img{
display:inline-block;
position: relative;
width: 230px;
height: 210px;
padding-right:7%;
padding-bottom: 6%;
box-sizing: content-box;
}
.gallery{
border-style: dashed;
border-width: 2px;
color: #5967b9;
padding: 10%;
}
div.gallery { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="Form1" method="post" role="form" class="form" enctype="multipart/form-data">
<label> <input type="text" id="albumname" name="albumname" class="form-control" placeholder="Album Name" required autofocus> </label>
<div class="input-group">
<label for="file-upload" class="custom-file-upload">
<i class="fa fa-cloud-upload" id="choosefiles"></i> Choose Files...
</label>
` <input id="file-upload" type="file" multiple/>
</div>
<div class="gallery"></div>
<button class="btn btn-lg block btn-primary btn-block btn-signin-upload" type="submit" id="buttonForm">Upload</button>
</form>
Really not sure what the problem is, but I would be grateful for any help. Thanks

Show a hidden div while making another hidden

I am looking for a way to toggle through three stacked div's where a button press will trigger an onclick function to make that specific div visible and hiding the others. I have included a jsfiddle below with the code I currently have any help on this would be amazing!
function togglediv(id1, id2, id3) {
var idOne = document.getElementById(id1);
var idTwo = document.getElementById(id2);
var idThree = document.getElementById(id3);
idOne.style.display = idOne.style.display == "block" ? "none" : "block";
idTwo.style.display = idTwo.style.display == "none";
idThree.style.display = idThree.style.display == "none";
}
<div class="table-responsive">
<button type="button" class="btn btn-primary" onclick="togglediv('inner-dung', 'inner-boss', 'inner-item')">
Dungeon
</button>
<button type="button" class="btn btn-primary" onclick="togglediv('inner-boss', 'inner-dung', 'inner-item')">
Boss
</button>
<button type="button" class="btn btn-primary" onclick="togglediv('inner-item', 'inner-dung', 'inner-boss')">
Item
</button>
</div>
<div id="search-dung">
<div id="inner-dung">
DUNGEON
</div>
<div id="inner-boss">
BOSS
</div>
<div id="inner-item">
ITEM
</div>
</div>
JSFiddle
You can pass the ID you want to show to the function, use a CSS class to toggle display: none/block, toggle that class on the element you click on and hide the rest by removing the class.
.table-responsive {
margin: 0px auto;
width: 90%;
}
#search-dung {
margin: 0px auto;
width: 90%;
height: 50%;
background-color: white;
border: 1px solid red;
}
#inner-dung,
#inner-item,
#inner-boss {
position: absolute;
margin: 0px auto;
width: 90%;
height: 50%;
background-color: white;
border: 1px solid red;
display: none;
}
#inner-dung.show,
#inner-item.show,
#inner-boss.show {
display: block;
}
<div class="table-responsive">
<button type="button" onclick="togglediv('inner-dung')">
Dungeon
</button>
<button type="button" onclick="togglediv('inner-boss')">
Boss
</button>
<button type="button" onclick="togglediv('inner-item')">
Item
</button>
</div>
<div id="search-dung">
<div id="inner-dung">
DUNGEON
</div>
<div id="inner-boss">
BOSS
</div>
<div id="inner-item">
ITEM
</div>
</div>
<script>
var els = document.getElementById('search-dung').getElementsByTagName('div');
function togglediv(id) {
var el = document.getElementById(id);
for (var i = 0; i < els.length; i++) {
var cur = els[i];
if (cur.id == id) {
cur.classList.toggle('show')
} else {
cur.classList.remove('show');
}
}
}
</script>
function togglediv(id1, id2, id3) {
var idOne = document.getElementById(id1);
var idTwo = document.getElementById(id2);
var idThree = document.getElementById(id3);
idOne.style.display = "block";
idTwo.style.display = "none";
idThree.style.display = "none";
}
https://codepen.io/anon/pen/NjOpJw
a couple of of problems there.
use onClick rather than onclick
idOne.style.display = idOne.style.display == "block" ? "none" : "block"; will return a boolean so you should change it for this
idOne.style.display = "block";
set your javascript to load in the body.
here's a working version
https://jsfiddle.net/83qwrk70/1/
You can use a switch case, passing only the element you want to show in toggle div
//index.html
<button type="button" class="btn btn-primary" onclick="togglediv('inner-dung')">
Dungeon
</button>
<button type="button" class="btn btn-primary" onclick="togglediv('inner-boss')">
Boss</button>
<button type="button" class="btn btn-primary" onclick="togglediv('inner-item')">
Item </button>
//index.js
function show(el) {
el.style.display = 'block';
}
function hide(el) {
el.style.display = 'none';
}
function togglediv(selected) {
var idOne = document.getElementById('inner-dung');
var idTwo = document.getElementById('inner-boss');
var idThree = document.getElementById('inner-item');
switch(selected) {
case 'inner-dung': {
show(idOne);
hide(idTwo);
hide(idThree);
break;
}
case 'inner-boss': {
hide(idOne);
show(idTwo);
hide(idThree);
break;
}
case 'inner-item': {
hide(idOne);
hide(idTwo);
show(idThree);
break;
}
}
}
Here is another option that is scaleable:
var active = "inner-dung",
inactive = ["inner-boss", "inner-item"];
var toggleDiv = function (id) {
active = inactive.splice(inactive.indexOf(id), 1, active);
document.getElementById(active).style.display = "block"; // or use style sheet
for (var i = 0; i < inactive.length; i++) {
document.getElementById(inactive[i]).style.display = "none"; // or use style sheet
}
}
If there is no default active item, you can put "inner-dung" in the array as well. If you do that, the "inactive" array will receive "undefined" the first time, but it will not get in the way of the purpose.
You don't have to use a for-loop of course, but if you have more items you would.
"Teach your children well"
Apply a rule to the parent to influence the children.
document.querySelector( "form" ).addEventListener( "click", function( evt ) {
var n = evt.target.name;
if ( n ) {
document.querySelector( "#foobarbaz" ).setAttribute( "class", n );
}
}, false );
#foo,
#bar,
#baz {
display: none;
}
#foobarbaz.foo #foo,
#foobarbaz.bar #bar,
#foobarbaz.baz #baz {
display: block;
}
<div id="foobarbaz" class="foo">
<div id="foo">Foo!</div>
<div id="bar">Bar?</div>
<div id="baz">Baz.</div>
</div>
<form>
<input type="button" value="Foo" name="foo">
<input type="button" value="Bar" name="bar">
<input type="button" value="Baz" name="baz">
</form>

Categories

Resources