Why is the content being appended to the wrong dynamically-generated tab? - javascript

I am trying to create jQuery Tabs dynamically. It should work so that every time I click on "Generate" Multiplication table button a new Tab should be created and a table with the current data parameters will be displayed in this tab.
Currently, the first tab stores all the tables, and the subsequent tabs do not store anything:
How can I make the first tab store only the first table and the second tab the next table and so on?
$( document ).ready(function() {
var tabs = [];
//Function to generate a multiplication table based on user's range input.
function generateTable(minCol, maxCol, minRow, maxRow) {
let tabsList = document.getElementById("tabsList");
let tableTabs = document.getElementById("tableTabs");
let tabObject = {
name: tabs.length,
minCol: minCol,
maxCol: maxCol,
minRow: minRow,
maxRow: maxRow
};
tabs.push(tabObject);
let listItem = document.createElement("li");
let anchor = document.createElement("a");
anchor.href = `#tab-${tabs.length-1}`;
anchor.innerText = `tab-${tabs.length-1}`;
listItem.appendChild(anchor);
tabsList.appendChild(listItem);
listItem.classList.add("ui-tabs-tab");
let tableDiv = document.createElement("div");
tableDiv.id = `tab-${tabs.length-1}`;
tableTabs.appendChild(tableDiv);
var error = document.getElementById("message");
var table = document.createElement("table");
var result = "";
//creating a multTable
for(var i=minRow; i<=maxRow;i++)
{
if(i==minRow)
{
result += "<tr>";
result += "<th>×</th>";
}
for(var j=minCol; j<=maxCol; j++)
{
if(i==minRow || j==minCol)
{
if(i==minRow)
result += "<th>" + j + "</th>";
else
result += "<td>"+ (i-1)*j + "</td>";
}
else
result += "<td>"+ (i-1)*j + "</td>";
}
result += "</tr>";
result += "<tr>";
result += "<th>" + i + "</th>";
if(i==maxRow)
{
for(var j=minCol; j<=maxCol; j++)
{
result += "<td>"+ i*j + "</td>";
}
}
}
//printing the table
table.innerHTML=result;
tableDiv.appendChild(table);
$("#tableTabs").tabs( { "active" : tabs.length-1});
return false;
}
//Function to validate user's input
$(function() {
$("#inputForm").submit(function(e) {
e.preventDefault();
}).validate({
submitHandler: function(form) {
var minCol = parseInt(document.getElementById("minCol").value);
var maxCol = parseInt(document.getElementById("maxCol").value);
var minRow = parseInt(document.getElementById("minRow").value);
var maxRow = parseInt(document.getElementById("maxRow").value);
generateTable(minCol, maxCol, minRow, maxRow);
return false;
}
});//end validate
});//end function
});
html {
background-color: #9FA5FF;
height: 100%;
}
body {
background-color: #E2E3FF;
margin: 0 auto;
width: 70%;
}
h2 {
padding-top: 20px;
padding-bottom: 20px;
text-align: center;
background-color: #c68de2;
}
h6 {
text-align: center;
margin-bottom: 0px;
}
.purple-background {
background-color:#c68de2;
}
.black {
color:#000000;
}
.inputfield{
height:30px;
}
.containerInput {
padding-left: 0px;
padding-right: 0px;
}
.container {
padding: 20px 0;
overflow: scroll;
height: 400px;
}
#multTable {
margin: auto;
}
#multTable td, th {
width: 50px;
font-size: 20px;
border: 1px solid blue;
}
#multTable td:nth-child(even) {
background-color: #ffffff;
}
#multTable th {
background-color: #9FA5FF;
}
#message p{
color: red;
margin-bottom: 0px;
padding-top: 15px;
padding-left: 15px;
text-align: center;
}
.error {
color: red;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Multiplication table</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.theme.min.css" integrity="sha512-9h7XRlUeUwcHUf9bNiWSTO9ovOWFELxTlViP801e5BbwNJ5ir9ua6L20tEroWZdm+HFBAWBLx2qH4l4QHHlRyg==" crossorigin="anonymous" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" integrity="sha512-aOG0c6nPNzGk+5zjwyJaoRUgCdOrfSDhmMID2u4+OIslr0GjpLKo7Xm0Ao3xmpM4T8AmIouRkqwj1nrdVsLKEQ==" crossorigin="anonymous" />
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.2/jquery.validate.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="js/validate.js"></script>
</head>
<body>
<div class="containerInput">
<h2>Multiplication Table</h2>
<div class="row justify-content-center">
<div class="col-lg-6 col-md-6-offset-3 col-sm-12 well" >
<form id="inputForm" class = 'card p-3 bg-light' class="form-horizontal">
<h6>Please enter range values for your Multiplication Table.</h6>
<hr>
<div class="form-group">
<label class="control-label col-sm-10" for="minCol">Minimum Column Value:</label>
<div class="col-sm-12">
<input class="form-control inputfield" id="minCol" name="minCol" value="-50">
</div>
<div id="minColSlider" class="sliderMC"></div>
</div>
<div class="form-group">
<label class="control-label col-sm-10" for="maxCol">Maximum Column Value:</label>
<div class="col-sm-12">
<input class="form-control inputfield" id="maxCol" name="maxCol" value="-50">
</div>
<div id="maxColSlider" class="sliderMC2"></div>
</div>
<div class="form-group">
<label class="control-label col-sm-10" for="minRow">Minimum Row Value:</label>
<div class="col-sm-12">
<input class="form-control inputfield" id="minRow" name="minRow" value="-50">
</div>
<div id="minRowSlider" class="sliderMR"></div>
</div>
<div class="form-group">
<label class="control-label col-sm-10" for="maxRow">Maximum Row Value:</label>
<div class="col-sm-12">
<input class="form-control inputfield" id="maxRow" name="maxRow" value="-50">
</div>
<div id="maxRowSlider" class="sliderMR2"></div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-secondary purple-background black">Generate</button>
</div>
</div>
</form>
</div>
</div>
</div>
<div id="message">
</div>
<div id="tableTabs">
<ul id="tabsList">
</ul>
</div>
</body>
</html>
Fiddle demo

Re-initialization of the tabs is failing. You need to destroy them if they exist first.
if ($('#tableTabs').tabs()) {
$("#tableTabs").tabs('destroy');
}
$("#tableTabs").tabs({
"active": tabs.length - 1
});
Also note that your table markup is incomplete. It's lacking a closing table row tag:
<tr><th>×</th><th>-50</th></tr><tr><th>-50</th><td>2500</td>
$( document ).ready(function() {
var tabs = [];
//Function to generate a multiplication table based on user's range input.
function generateTable(minCol, maxCol, minRow, maxRow) {
let tabsList = document.getElementById("tabsList");
let tableTabs = document.getElementById("tableTabs");
let tabObject = {
name: tabs.length,
minCol: minCol,
maxCol: maxCol,
minRow: minRow,
maxRow: maxRow
};
tabs.push(tabObject);
let listItem = document.createElement("li");
let anchor = document.createElement("a");
anchor.href = `#tab-${tabs.length-1}`;
anchor.innerText = `tab-${tabs.length-1}`;
listItem.appendChild(anchor);
tabsList.appendChild(listItem);
listItem.classList.add("ui-tabs-tab");
let tableDiv = document.createElement("div");
tableDiv.id = `tab-${tabs.length-1}`;
tableTabs.appendChild(tableDiv);
var error = document.getElementById("message");
var table = document.createElement("table");
var result = "";
//creating a multTable
for(var i=minRow; i<=maxRow;i++)
{
if(i==minRow)
{
result += "<tr>";
result += "<th>×</th>";
}
for(var j=minCol; j<=maxCol; j++)
{
if(i==minRow || j==minCol)
{
if(i==minRow)
result += "<th>" + j + "</th>";
else
result += "<td>"+ (i-1)*j + "</td>";
}
else
result += "<td>"+ (i-1)*j + "</td>";
}
result += "</tr>";
result += "<tr>";
result += "<th>" + i + "</th>";
if(i==maxRow)
{
for(var j=minCol; j<=maxCol; j++)
{
result += "<td>"+ i*j + "</td>";
}
}
}
//printing the table
table.innerHTML=result;
tableDiv.appendChild(table);
if ($('#tableTabs').tabs()) {
$("#tableTabs").tabs('destroy');
}
$("#tableTabs").tabs( { "active" : tabs.length-1});
return false;
}
//Function to validate user's input
$(function() {
$("#inputForm").submit(function(e) {
e.preventDefault();
}).validate({
submitHandler: function(form) {
var minCol = parseInt(document.getElementById("minCol").value);
var maxCol = parseInt(document.getElementById("maxCol").value);
var minRow = parseInt(document.getElementById("minRow").value);
var maxRow = parseInt(document.getElementById("maxRow").value);
generateTable(minCol, maxCol, minRow, maxRow);
return false;
}
});//end validate
});//end function
});
html {
background-color: #9FA5FF;
height: 100%;
}
body {
background-color: #E2E3FF;
margin: 0 auto;
width: 70%;
}
h2 {
padding-top: 20px;
padding-bottom: 20px;
text-align: center;
background-color: #c68de2;
}
h6 {
text-align: center;
margin-bottom: 0px;
}
.purple-background {
background-color:#c68de2;
}
.black {
color:#000000;
}
.inputfield{
height:30px;
}
.containerInput {
padding-left: 0px;
padding-right: 0px;
}
.container {
padding: 20px 0;
overflow: scroll;
height: 400px;
}
#multTable {
margin: auto;
}
#multTable td, th {
width: 50px;
font-size: 20px;
border: 1px solid blue;
}
#multTable td:nth-child(even) {
background-color: #ffffff;
}
#multTable th {
background-color: #9FA5FF;
}
#message p{
color: red;
margin-bottom: 0px;
padding-top: 15px;
padding-left: 15px;
text-align: center;
}
.error {
color: red;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Multiplication table</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.theme.min.css" integrity="sha512-9h7XRlUeUwcHUf9bNiWSTO9ovOWFELxTlViP801e5BbwNJ5ir9ua6L20tEroWZdm+HFBAWBLx2qH4l4QHHlRyg==" crossorigin="anonymous" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" integrity="sha512-aOG0c6nPNzGk+5zjwyJaoRUgCdOrfSDhmMID2u4+OIslr0GjpLKo7Xm0Ao3xmpM4T8AmIouRkqwj1nrdVsLKEQ==" crossorigin="anonymous" />
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.2/jquery.validate.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="js/validate.js"></script>
</head>
<body>
<div class="containerInput">
<h2>Multiplication Table</h2>
<div class="row justify-content-center">
<div class="col-lg-6 col-md-6-offset-3 col-sm-12 well" >
<form id="inputForm" class = 'card p-3 bg-light' class="form-horizontal">
<h6>Please enter range values for your Multiplication Table.</h6>
<hr>
<div class="form-group">
<label class="control-label col-sm-10" for="minCol">Minimum Column Value:</label>
<div class="col-sm-12">
<input class="form-control inputfield" id="minCol" name="minCol" value="-50">
</div>
<div id="minColSlider" class="sliderMC"></div>
</div>
<div class="form-group">
<label class="control-label col-sm-10" for="maxCol">Maximum Column Value:</label>
<div class="col-sm-12">
<input class="form-control inputfield" id="maxCol" name="maxCol" value="-50">
</div>
<div id="maxColSlider" class="sliderMC2"></div>
</div>
<div class="form-group">
<label class="control-label col-sm-10" for="minRow">Minimum Row Value:</label>
<div class="col-sm-12">
<input class="form-control inputfield" id="minRow" name="minRow" value="-50">
</div>
<div id="minRowSlider" class="sliderMR"></div>
</div>
<div class="form-group">
<label class="control-label col-sm-10" for="maxRow">Maximum Row Value:</label>
<div class="col-sm-12">
<input class="form-control inputfield" id="maxRow" name="maxRow" value="-50">
</div>
<div id="maxRowSlider" class="sliderMR2"></div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-secondary purple-background black">Generate</button>
</div>
</div>
</form>
</div>
</div>
</div>
<div id="message">
</div>
<div id="tableTabs">
<ul id="tabsList">
</ul>
</div>
</body>
</html>

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)
})

JavaScript DOM table manipulation

First Problem
How to modify the function cut() to apply "line-through" to all td elements not for only the first.
Second Problem
When I generate the table I don't know what I'm missing in this.details to automatically generate the th of the table only one time (not to display in html like in the code below) because I tried
this.details = `<tr>
<th>Item description<\th>
<th>Action<\th>
<td>${this.item}</td>
<td>${this.action}</td>
</tr>`;
and the th is generate for each td.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="style.css">
<title>list</title>
</head>
<body>
<h2>list</h2>
<div class="container">
<input type="text" name="item" id="item">
<label for="item"></label>
<input type="button" value="Add item" class="addBtn" id="add">
</div>
<div class="container" id="sort">
<input type="button" value="Sort asc" class="btn">
<input type="button" value="Sort desc" class="btn">
</div>
<div class="tableData" id="table">
<table id="display-none">
<tr>
<th class="show-succes">product</th>
<th class="show-succes">mark</th>
</tr>
</div>
<script src="app.js"></script>
</body>
</html>
function Item(item, action, table) {
this.item = item;
this.action = `<input type="button" value="Mark as buyed" class="newBtn" id="buton" onclick="cut()" `;
this.details = `<tr>
<td>${this.item}</td>
<td>${this.action}</td>
</tr>`;
this.table = table;
this.addToTable = function () {
this.table.innerHTML += this.details;
};
}
const addBtn = document.getElementById('add');
addBtn.addEventListener('click', addNewItem);
function addNewItem() {
const items = document.getElementById('item').value;
const actions = 'mark as buyed'
const myTable = document.getElementById('display-none');
const item = new Item(items, actions, myTable);
item.addToTable();
}
function cut() {
let el = document.querySelector("td");
el.style.textDecoration = "line-through";
}
*{
margin: 0px;
padding: 0px;
box-sizing: border-box;
text-decoration: none;
}
h2 {
text-align: center;
padding: 60px ;
}
input[type="text"]{
margin-right: 20px;
}
label{
padding: 15px;
}
.btn{
padding: 5px;
margin-top: 20px;
margin-right: 10px;
}
#sort{
margin-left: -90px;
}
.container{
display: flex;
justify-content: center;
}
#table{
width: 40%;
text-align: center;
margin-left: 650px;
margin-top: 20px;
}
Your approach is much more involved than necessary and really wouldn't do you any good to try to fix it.
See comments inline below for the most simple approach.
// Get reference to the elements you'll use
// over and over, just once.
const input = document.getElementById("item");
const tbl = document.querySelector("table");
const add = document.querySelector(".addBtn");
// Add an event handler for the add button click
add.addEventListener("click", function(){
let row = tbl.insertRow(); // Add a row to the table
let itemCell = row.insertCell(); // Add a td to the row
itemCell.textContent = input.value; // Put the input value in the td
let actionCell = row.insertCell(); // Add a second td to the row
let chk = document.createElement("input"); // Create a new input
chk.type = "checkbox"; // Make the input a checkbox
chk.value = "bought"; // Set a value for the checkbox
// Set up an event handler for the new checkbox
chk.addEventListener("click", function(){
// Find the nearest ancestor tr and then query it
// for the first td in it. Then toggle the use of the
// "strike" CSS class to add or remove strikethrough.
this.closest("tr").querySelector("td").classList.toggle("strike");
});
actionCell.appendChild(chk); // Add the checkbox to the td
input.value = ""; // Clear out the textbox
tbl.classList.remove("hidden"); // Show the table
});
body {
font-family:Calibri, Helvetica, Arial;
}
h1 {
font-size:1.8em;
}
div {
margin:1em;
}
.strike {
text-decoration-line: line-through;
}
.hidden {
display:none;
}
<h1>SHOPPING LIST</h1>
<div class="addItems">
<input type="text" id="item">
<input type="button" value="Add item" class="addBtn">
</div>
<table class="hidden">
<tr>
<th>Item</th>
<th>Bought?</th>
</tr>
</table>

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

Why does my page refresh when I press buttons?

This is the relevant code of my page :
HTML :
<button class="ajout-col"><i class="fas fa-columns"> Ajouter une colonne</i></button>
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th></th>
<th>
<button class="btn"><i class="fas fa-trash remove-col"></i></button>
<button class="btn"><i class="fas fa-text-height text-col"></i></button>
<button class="btn"><i class="fas fa-sort-numeric-down nbr-col"></i></button>
<input type="text" class="form-control">
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<button class="btn"><i class="fas fa-trash remove-row"></i></button>
</td>
<td>
<input type="text" class="form-control">
</td>
</tr>
</tbody>
</table>
</div>
<button class="ajout-lig"><i class="fas fa-list-ul"> Ajouter une ligne</i></button>
Javascript :
$('body').on('click', '.remove-row', function() {
$(this).parents('tr').remove();
});
(Any button of the grid refreshes my page, I just put the remove-row one because it's the shortest code only for clarity purpose)
(Issue is located on the second tab, just fill info on the first tab to be able to access the second tab)
Any time I press a button from the grid, it refreshes my page
I searched on google and it appears I have to add "return false" or "e.preventDefault();" to fix the issue, and I tried, but it only fixes partially the issue
If I add any of those at the end of each .on('click'), it fixes the issue for Adding a column or a row
But deleting a row or a column is going to work 1 or 2 times, and then my page is going to refresh again... same for the other buttons (text and number buttons)
Thanks in advance for any help ! :)
// Code goes here
$(document).ready(function() {
// add row
$('body').on('click', '.ajout-lig', function() {
var tr = $(this).parents('.table-content').find('.table tbody tr:last');
if (tr.length > 0) {
var clone = tr.clone();
clone.find(':text').val('');
tr.after(clone);
} else {
var cols = $(this).closest('.table-content').find('th').length,
tr0 = $('<tr/>');
tr0.html('<td><button class="btn"><i class="fa fa-trash remove-row"></i></button></td><td> <input type="text" class="form-control"> </td>');
for (var i = 2; i < cols; i++) {
tr0.append('<td> static element </td>')
}
$(this).closest('.table-content').find('.table tbody').append(tr0);
}
});
// delete row
$('body').on('click', '.remove-row', function() {
$(this).parents('tr').remove();
});
// add column
$('body').on('click', '.ajout-col', function() {
$(this).parent().find('.table thead tr').append('<th><button class="btn"><i class="fas fa-trash remove-col"></i></button> <button class="btn"><i class="fas fa-text-height text-col"></i></button> <button class="btn"><i class="fas fa-sort-numeric-down nbr-col"></i></button> <input type="text" class="form-control pull-left" value=""></th>');
$(this).parent().find('.table tbody tr').append('<td><input type="text" class="form-control"></td>');
});
// change column type to text
$('body').on('click', '.text-col', function(event) {
let ndx = $(this).parent().index() + 1;
let inputsCol = $('.table tbody tr td:nth-child(' + ndx + ') input');
inputsCol.attr("type", "text");
});
// change column type to number
$('body').on('click', '.nbr-col', function(event) {
var filter = /^[0-9]*$/g;
var cond = false;
var min = prompt('Valeur minimum :');
while (cond == false) {
if (min.match(filter)) {
cond = true;
} else {
var min = prompt('Valeur minimum incorrect, réessayez :');
}
}
var cond = false;
var max = prompt('Valeur maximum :');
while (cond == false) {
if (max.match(filter)) {
cond = true;
} else {
var max = prompt('Valeur maximum incorrect, réessayez :');
}
}
let ndx = $(this).parent().index() + 1;
let inputsCol = $('.table tbody tr td:nth-child(' + ndx + ') input');
inputsCol.attr("type", "number").prop("min", min).prop("max", max);
//console.log("inputs modified, example:", inputsCol2[0])
});
// remove column
$('body').on('click', '.remove-col', function(event) {
// Get index of parent TD among its siblings (add one for nth-child)
var ndx = $(this).parent().index() + 1;
// Find all TD elements with the same index
$('th', event.delegateTarget).remove(':nth-child(' + ndx + ')');
$('td', event.delegateTarget).remove(':nth-child(' + ndx + ')');
});
});
$(document).ready(function(){
$('#btn_login_details').click(function(){
var error_date = '';
var error_titre = '';
var error_entreprise = '';
var error_conseiller = '';
var filter = /^([0-2][0-9]|(3)[0-1])(\/)(((0)[0-9])|((1)[0-2]))(\/)\d{4}$/;
if($.trim($('#titre').val()).length == 0)
{
error_titre = 'Titre requis !';
$('#error_titre').text(error_titre);
$('#titre').addClass('has-error');
}
else
{
error_titre = '';
$('#error_titre').text(error_titre);
$('#titre').removeClass('has-error');
}
if($.trim($('#entreprise').val()).length == 0)
{
error_entreprise = 'Nom de l\'entreprise requis !';
$('#error_entreprise').text(error_entreprise);
$('#entreprise').addClass('has-error');
}
else
{
error_entreprise = '';
$('#error_entreprise').text(error_entreprise);
$('#entreprise').removeClass('has-error');
}
if($.trim($('#conseiller').val()).length == 0)
{
error_conseiller = 'Nom du conseiller requis !';
$('#error_conseiller').text(error_conseiller);
$('#conseiller').addClass('has-error');
}
else
{
error_conseiller = '';
$('#error_conseiller').text(error_conseiller);
$('#conseiller').removeClass('has-error');
}
if($.trim($('#date').val()).length == 0)
{
error_date = 'Date requise !';
$('#error_date').text(error_date);
$('#date').addClass('has-error');
}
else
{
if (!filter.test($('#date').val()))
{
error_date = 'Date invalide';
$('#error_date').text(error_date);
$('#date').addClass('has-error');
}
else
{
error_date = '';
$('#error_date').text(error_date);
$('#date').removeClass('has-error');
}
}
if((error_titre != '') || (error_conseiller != '') || (error_entreprise != '') || (error_date != ''))
{
return false;
}
else
{
$('#list_login_details').removeClass('active active_tab1');
$('#list_login_details').removeAttr('href data-toggle');
$('#login_details').removeClass('active');
$('#list_login_details').addClass('inactive_tab1');
$('#list_personal_details').removeClass('inactive_tab1');
$('#list_personal_details').addClass('active_tab1 active');
$('#list_personal_details').attr('href', '#personal_details');
$('#list_personal_details').attr('data-toggle', 'tab');
$('#personal_details').addClass('active in');
}
});
$('#previous_btn_personal_details').click(function(){
$('#list_personal_details').removeClass('active active_tab1');
$('#list_personal_details').removeAttr('href data-toggle');
$('#personal_details').removeClass('active in');
$('#list_personal_details').addClass('inactive_tab1');
$('#list_login_details').removeClass('inactive_tab1');
$('#list_login_details').addClass('active_tab1 active');
$('#list_login_details').attr('href', '#login_details');
$('#list_login_details').attr('data-toggle', 'tab');
$('#login_details').addClass('active in');
});
$('#btn_gen_grille').click(function() {
// Générer la grille
// Ici
});
$('#btn_personal_details').click(function(){
$('#list_personal_details').removeClass('active active_tab1');
$('#list_personal_details').removeAttr('href data-toggle');
$('#personal_details').removeClass('active');
$('#list_personal_details').addClass('inactive_tab1');
$('#list_contact_details').removeClass('inactive_tab1');
$('#list_contact_details').addClass('active_tab1 active');
$('#list_contact_details').attr('href', '#contact_details');
$('#list_contact_details').attr('data-toggle', 'tab');
$('#contact_details').addClass('active in');
});
$('#previous_btn_contact_details').click(function(){
$('#list_contact_details').removeClass('active active_tab1');
$('#list_contact_details').removeAttr('href data-toggle');
$('#contact_details').removeClass('active in');
$('#list_contact_details').addClass('inactive_tab1');
$('#list_personal_details').removeClass('inactive_tab1');
$('#list_personal_details').addClass('active_tab1 active');
$('#list_personal_details').attr('href', '#personal_details');
$('#list_personal_details').attr('data-toggle', 'tab');
$('#personal_details').addClass('active in');
});
$('#btn_contact_details').click(function(){
var error_address = '';
var error_mobile_no = '';
var mobile_validation = /^\d{10}$/;
if($.trim($('#address').val()).length == 0)
{
error_address = 'Address is required';
$('#error_address').text(error_address);
$('#address').addClass('has-error');
}
else
{
error_address = '';
$('#error_address').text(error_address);
$('#address').removeClass('has-error');
}
if($.trim($('#mobile_no').val()).length == 0)
{
error_mobile_no = 'Mobile Number is required';
$('#error_mobile_no').text(error_mobile_no);
$('#mobile_no').addClass('has-error');
}
else
{
if (!mobile_validation.test($('#mobile_no').val()))
{
error_mobile_no = 'Invalid Mobile Number';
$('#error_mobile_no').text(error_mobile_no);
$('#mobile_no').addClass('has-error');
}
else
{
error_mobile_no = '';
$('#error_mobile_no').text(error_mobile_no);
$('#mobile_no').removeClass('has-error');
}
}
if(error_address != '' || error_mobile_no != '')
{
return false;
}
else
{
$('#btn_contact_details').attr("disabled", "disabled");
$(document).css('cursor', 'prgress');
$("#register_form").submit();
}
});
});
/* Style the header with a grey background and some padding */
* {box-sizing: border-box;}
body {
margin: 0;
font-family: Arial, Helvetica, sans-serif;
}
.header {
overflow: hidden;
background-color: #f1f1f1;
padding: 20px 10px;
}
.header a {
float: left;
color: black;
text-align: center;
padding: 12px;
text-decoration: none;
font-size: 18px;
line-height: 25px;
border-radius: 4px;
}
.header a.logo {
font-size: 25px;
font-weight: bold;
}
.header a:hover {
background-color: #ddd;
color: black;
}
.header a.active {
background-color: dodgerblue;
color: white;
}
.header-right {
float: right;
}
#media screen and (max-width: 500px) {
.header a {
float: none;
display: block;
text-align: left;
}
.header-right {
float: none;
}
}
.contenuaccueil {
text-align: center;
position : absolute;
width : 100%;
color : black;
top:50%;
left:50%;
transform:translate(-50%,-50%);
}
.background
{
margin-top : 10%;
margin-bottom : 10%;
position:relative;
text-align: center;
}
.img
{
background-repeat: repeat-x;
width: 100%;
height: auto;
text-align: center;
}
footer {
text-align : center;
padding-top: 10px;
padding-bottom: 0px;
bottom:0;
width:100%;
color : #A5A5A5;
font-family : "Lato", sans-serif;
font-size : 15px;
font-weight : 400;
text-transform : uppercase;
text-decoration : none;
letter-spacing : 3px;
}
.box
{
width:800px;
margin:0 auto;
}
.active_tab1
{
background-color:#fff;
color:#333;
font-weight: 600;
}
.inactive_tab1
{
background-color: #f5f5f5;
color: #333;
cursor: not-allowed;
}
.has-error
{
border-color:#cc0000;
background-color:#ffff99;
}
/* Styles go here */
.table-content {
padding: 20px;
}
.form-control {
width: 90px;
}
/* Style buttons */
.ajout-lig,.ajout-col {
background-color: DodgerBlue; /* Blue background */
border: none; /* Remove borders */
color: white; /* White text */
padding: 12px 16px; /* Some padding */
font-size: 16px; /* Set a font size */
cursor: pointer; /* Mouse pointer on hover */
border-radius: 5px;
}
/* Darker background on mouse-over */
.ajout-lig:hover,.ajout-col:hover {
background-color: RoyalBlue;
}
<html>
<head>
<title>Innovatech</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="css/custom.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://kit.fontawesome.com/38b99a3f0e.js" crossorigin="anonymous"></script>
</head>
<body>
<!-- Titre + Menu -->
<div class="header">
Innovatech
<div class="header-right">
Accueil
<a class="active" href="ajout.php">Nouveau</a>
Modifier
Mode d'emploi
</div>
</div>
<!-- Contenu du site web -->
<div class="contenu">
<br />
<div class="container box">
<br />
<h2 align="center">Ajout d'un nouvel audit</h2><br />
<?php echo $message; ?>
<form method="post" id="register_form">
<ul class="nav nav-tabs">
<li class="nav-item">
<a class="nav-link active_tab1" style="border:1px solid #ccc" id="list_login_details">Informations à propos de l'entreprise</a>
</li>
<li class="nav-item">
<a class="nav-link inactive_tab1" id="list_personal_details" style="border:1px solid #ccc">Grille d'audit</a>
</li>
<li class="nav-item">
<a class="nav-link inactive_tab1" id="list_contact_details" style="border:1px solid #ccc">Génération des graphiques</a>
</li>
</ul>
<div class="tab-content" style="margin-top:16px;">
<div class="tab-pane active" id="login_details">
<div class="panel panel-default">
<div class="panel-heading">Informations à propos de l'entreprise</div>
<div class="panel-body">
<div class="form-group">
<label>Titre de l'audit</label>
<input type="text" name="titre" id="titre" class="form-control" />
<span id="error_titre" class="text-danger"></span>
</div>
<div class="form-group">
<label>Nom de l'entreprise</label>
<input type="text" name="entreprise" id="entreprise" class="form-control" />
<span id="error_entreprise" class="text-danger"></span>
</div>
<div class="form-group">
<label>Nom du conseiller</label>
<input type="text" name="conseiller" id="conseiller" class="form-control" />
<span id="error_conseiller" class="text-danger"></span>
</div>
<div class="form-group">
<label>Date de l'interview (jj/mm/aaaa)</label>
<input type="text" name="date" id="date" class="form-control" />
<span id="error_date" class="text-danger"></span>
</div>
<br />
<div align="center">
<button type="button" name="btn_login_details" id="btn_login_details" class="btn btn-info btn-lg">Suivant</button>
</div>
<br />
</div>
</div>
</div>
<div class="tab-pane fade" id="personal_details">
<div class="panel panel-default">
<div class="panel-heading">Grille d'audit</div>
<div class="panel-body">
<div class="table-content">
<button class="ajout-col"><i class="fas fa-columns"> Ajouter une colonne</i></button>
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th></th>
<th>
<button class="btn"><i class="fas fa-trash remove-col"></i></button>
<button class="btn"><i class="fas fa-text-height text-col"></i></button>
<button class="btn"><i class="fas fa-sort-numeric-down nbr-col"></i></button>
<input type="text" class="form-control">
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<button class="btn"><i class="fas fa-trash remove-row"></i></button>
</td>
<td>
<input type="text" class="form-control">
</td>
</tr>
</tbody>
</table>
</div>
<button class="ajout-lig"><i class="fas fa-list-ul"> Ajouter une ligne</i></button>
</div>
<br />
<div align="center">
<button type="button" name="previous_btn_personal_details" id="previous_btn_personal_details" class="btn btn-default btn-lg">Précédent</button>
<button type="button" name="btn_personal_details" id="btn_personal_details" class="btn btn-info btn-lg">Suivant</button>
</div>
<br />
</div>
</div>
</div>
<!--A MODIFIER - PARTIE SUR LES GRAPHIQUES-->
<div class="tab-pane fade" id="contact_details">
<div class="panel panel-default">
<div class="panel-heading">Fill Contact Details</div>
<div class="panel-body">
<div class="form-group">
<label>Enter Address</label>
<textarea name="address" id="address" class="form-control"></textarea>
<span id="error_address" class="text-danger"></span>
</div>
<div class="form-group">
<label>Enter Mobile No.</label>
<input type="text" name="mobile_no" id="mobile_no" class="form-control" />
<span id="error_mobile_no" class="text-danger"></span>
</div>
<br />
<div align="center">
<button type="button" name="previous_btn_contact_details" id="previous_btn_contact_details" class="btn btn-default btn-lg">Précédent</button>
<button type="button" name="btn_contact_details" id="btn_contact_details" class="btn btn-success btn-lg">Enregistrer</button>
</div>
<br />
</div>
</div>
</div>
</div>
</form>
</div>
</div>
<!-- Le pied de page -->
<footer>
<p>
Innovatech <?php echo date("Y");?> - All rights reserved
</p>
</footer>
<script src="jss/ajout.js"></script>
<script src="jss/gengrille.js"></script>
</body>
</html>
This happens because a button with no type attribute acts as type="submit" and also try to submit the form data to server and refresh the page finally. Please try to set the type to the buttons like type="button" for no page refreshes.
<button class="ajout-col" type="button">
<i class="fas fa-columns"> Ajouter une colonne</i>
</button>
Replace <button class="ajout-lig"><i class="fas fa-list-ul"> Ajouter une ligne</i></button>
to
<button class="ajout-lig" type="button"><i class="fas fa-list-ul"> Ajouter une ligne</i></button>
I think this problem is due to, these buttons are actually submitting the form. if we doesn't specify the button type, it will take as a submit type button

Jquery change colors with recursion

Here is jsfiddle of raw code and the result should be like this
<div class="wrapper">
<div class="row">
<div class="col red">R</div>
<div class="col blue">B</div>
<div class="col green">G</div>
<div class="col orange">O</div>
</div>
</div>
The mission is: Last color of previous row should be the first in next row and first color from previuos row should be the second in next row.
I think that I have to use loop and recursion but I don't have enough knowledge to do this.
Thanks in advance :)
You can run through the for loop and do something like this
check this snippet
//last color of previous row should be first in next row
//first color from previous row should be second in next row
var colors = ['red', 'blue', 'green', 'orange'];
$(document).ready(function() {
var rows = $('.row');
rows.each(function(row) {
var index = $(this).index();
var prevRow;
if (index > 0)
prevRow = $(this).prev();
colorColumns($(this).find('.col'), prevRow);
});
});
function colorColumns(cols, prevRow) {
var index = 0;
// alert("hi");
cols.each(function(col) {
var colIndex = $(this).index();
if (prevRow) {
var cols = prevRow.find('.col').length;
var totalCols = cols - 1;
var currentIndex = ((colIndex + totalCols) % cols);
var prevRowColor = $(prevRow).find('.col').eq(currentIndex);
var classes = prevRowColor.attr('class');
var classArr = classes.split(" ");
$(this).addClass(classArr[1]);
} else {
$(this).addClass(colors[colIndex]);
}
});
}
.row {
display: flex;
}
.row .col {
width: 20px;
height: 20px;
border-radius: 100%;
text-align: center;
}
.red {
background: red;
}
.orange {
background: orange;
}
.blue {
background: blue;
}
.green {
background: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
<div class="row">
<div class="col">R</div>
<div class="col">B</div>
<div class="col">G</div>
<div class="col">O</div>
</div>
<div class="row">
<div class="col">R</div>
<div class="col">B</div>
<div class="col">G</div>
<div class="col">О</div>
</div>
<div class="row">
<div class="col">R</div>
<div class="col">B</div>
<div class="col">G</div>
<div class="col">O</div>
</div>
Hope it helps

Categories

Resources