js row length needs to reset after row removal - javascript

He, i'm almost done with my project but i still have one problem.
when i am removing a table row dynamically, the row count is going terrible wrong. i thought i had the solution for this problem.
how should i reset the row count for the rows after a row remove.
can some one explain what i am doing wrong ?
var btn = document.getElementById("btn");
var table = document.getElementById("table");
var removeRowBtn = document.getElementById("removeRowBtn");
// input fields Variable
var firstName = document.myForm.firstName;
var lastName = document.myForm.lastName;
var Age = document.myForm.Age;
var Country = document.myForm.Country;
var row = document.getElementById("table").getElementsByTagName("tr");
btn.onclick = function() {
addData()
};
// this function is checking if the input fields have the recuired data in it other wise it give's a error.
function validate() {
// first name field check + error
if (document.myForm.firstName.value == "") {
alert("Please provide your first name!");
document.myForm.firstName.focus();
return false;
}
// last name field check + error message
if (document.myForm.lastName.value == "") {
alert("Please provide your last name!");
document.myForm.lastName.focus();
return false;
}
// age field check + error message
if (isNaN(document.myForm.Age.value) || document.myForm.Age.value < 1 || document.myForm.Age.value > 100) {
alert("Please provide your age!");
return false;
}
// country select list check + error message
if (document.myForm.Country.value == "chooseCountry") {
alert("Please provide your country!");
return false;
}
// if evry thing is true return a value of true
return true;
}
function addData() {
if (validate()) {
// creating a new tr
var tr = document.createElement("tr");
// adding the created elements to a object with a class name
table.appendChild(tr);
var rows = " ";
rows += "<td>" + row.length + "</td><td>" + firstName.value + "</td><td>" + lastName.value + "</td><td>" + age.value + "</td><td>" + country.value + "</td>";
tr.innerHTML = rows;
//console.log(row.length, " 'row length' ");
//console.log(firstName.value, " 'firstname value' ");
//console.log(lastName.value, " 'lastName value' ");
//console.log(age.value, " 'age value' ");
//console.log(country.value, " 'country value' ");
}
}
function removeTableRow() {
var tableNr = document.getElementById("tableNr");
i = tableNr.value - 1;
// if there is no table number filled in show a error alert
if (i == "") {
alert("Please provide a table number!");
tableNr.focus();
return false;
}
// find the chosen array
var row = table.getElementsByTagName("tr")[i];
// if the number is not in the row show error alert that it issen't in the table
if (row == undefined) {
alert("this row number is not in the table");
return false;
}
// remove the selected row
row.remove(row.selectedIndex);
// rework the row length
for (var i = 0; i < row.length; i++) {
rows[i].cells[0].innerText = row.length;
}
console.log(row.length, " 'row lenght' ");
}
removeRowBtn.onclick = function() {
removeTableRow()
};
body {
background: white;
}
img {
height: 100%;
display: block;
margin: 0 auto;
}
p {
text-align: center;
}
.container {
width: 100%;
max-width: 600px;
border-radius: 2px;
margin: 0 auto;
margin-top: 8vh;
background: lightgray;
box-shadow: 0px 4px 4px darkgray;
}
table {
width: 100%;
text-align: center;
}
td,
th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
/* Button */
.btn {
display: inline-block;
margin: 1em auto;
font-weight: 100;
padding: 1em 1.25em;
text-align: center;
width: 100%;
border-radius: 1px;
position: relative;
z-index: 0;
cursor: pointer;
border: none;
background: #0c84e4;
box-shadow: 0px 1px 1px #063e6b;
color: #FFFFFF;
}
:focus {
outline: -webkit-focus-ring-color auto 0px;
}
.btn.red {
background: red;
width: 100%;
}
/* input field style's */
input[type=text] {
width: calc(25% - 8px);
padding: 12px 20px 12px 5px;
margin: 8px 4px;
box-sizing: border-box;
float: left;
border: none;
border-bottom: 2px solid #536DFE;
text-align: center;
background: transparent;
}
input:focus {
outline: none;
color: black;
}
::-webkit-input-placeholder {
color: black;
font: helvetica 12px bold;
text-align: center;
}
select {
width: calc(25% - 8px);
padding: 12px 20px 12px 5px;
margin: 8px 4px;
box-sizing: border-box;
float: left;
border: none;
border-bottom: 2px solid #536DFE;
text-align: center;
background: transparent;
height: 39px;
border-radius: 0px !important;
}
<!DOCTYPE html>
<html>
<head>
<title>Inzend Opgave H5</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<!-- style sheets -->
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="wrapper">
<section class="container">
<form id="personInfo" name="myForm">
<table>
<thead>
<tr>
<td>nr.</td>
<td>First Name</td>
<td>Last Name</td>
<td>Age</td>
<td>Country</td>
</tr>
</thead>
<tbody id="table">
</tbody>
</table>
<input type="text" name="firstName" placeholder="firstName" id="firstName">
<input type="text" name="lastName" placeholder="lastName" id="lastName">
<input type="text" name="Age" placeholder="Age" id="age">
<select name="Country" id="country">
<option value="choose a country">Kies een land</option>
<option value="Nederland">NL</option>
<option value="Belgie">BE</option>
<option value="Duitsland">DE</option>
</select>
<input type="button" name="button" id="btn" class="btn" value="Add the input fields to the table">
<p>To remove a table number fill in the input field with the <br> number of the table and click remove table row</p>
<input type="button" name="button" id="removeRowBtn" class="btn" value="remove table row" style="width: 75%;">
<input type="text" name="TableNr" id="tableNr" placeholder="table nr.">
</form>
</section>
</div>
<!-- java-scripts -->
<script type="text/javascript" src="script.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.2.js"></script>
<script type="text/javascript">
var cw = $('.container').width();
$('.container').css({
'height': cw + 'px'
});
</script>
</body>
</html>

Bellow Snippet will give you the answer. However there is a small error on this row remove function. The user must know row index is starting at 0 to get the 1st row. Otherwise a wrong row will be deleted.
var btn = document.getElementById("btn");
var table = document.getElementById("table");
var removeRowBtn = document.getElementById("removeRowBtn");
// input fields Variable
var firstName = document.myForm.firstName;
var lastName = document.myForm.lastName;
var Age = document.myForm.Age;
var Country = document.myForm.Country;
var row = document.getElementById("table").getElementsByTagName("tr");
btn.onclick = function() {
addData()
};
// this function is checking if the input fields have the recuired data in it other wise it give's a error.
function validate() {
// first name field check + error
if (document.myForm.firstName.value == "") {
alert("Please provide your first name!");
document.myForm.firstName.focus();
return false;
}
// last name field check + error message
if (document.myForm.lastName.value == "") {
alert("Please provide your last name!");
document.myForm.lastName.focus();
return false;
}
// age field check + error message
if (isNaN(document.myForm.Age.value) || document.myForm.Age.value < 1 || document.myForm.Age.value > 100) {
alert("Please provide your age!");
return false;
}
// country select list check + error message
if (document.myForm.Country.value == "chooseCountry") {
alert("Please provide your country!");
return false;
}
// if evry thing is true return a value of true
return true;
}
function addData() {
if (validate()) {
// creating a new tr
var tr = document.createElement("tr");
// adding the created elements to a object with a class name
table.appendChild(tr);
var rows = " ";
rows += "<td>" + row.length + "</td><td>" + firstName.value + "</td><td>" + lastName.value + "</td><td>" + age.value + "</td><td>" + country.value + "</td>";
tr.innerHTML = rows;
//console.log(row.length, " 'row length' ");
//console.log(firstName.value, " 'firstname value' ");
//console.log(lastName.value, " 'lastName value' ");
//console.log(age.value, " 'age value' ");
//console.log(country.value, " 'country value' ");
}
}
function removeTableRow() {
var tableNr = document.getElementById("tableNr");
i = tableNr.value;
// if there is no table number filled in show a error alert
if (i == "") {
alert("Please provide a table number!");
tableNr.focus();
return false;
}
// find the chosen array
var row = table.getElementsByTagName("tr")[i];
// if the number is not in the row show error alert that it issen't in the table
if (row == undefined) {
alert("this row number is not in the table");
return false;
}
// remove the selected row
row.remove(row.selectedIndex);
row = document.getElementById("table").getElementsByTagName("tr");
// rework the row length
for (var i = 0; i < row.length; i++) {
row[i].cells[0].innerText = i+1;
}
console.log("Row length: "+ row.length);
}
removeRowBtn.onclick = function() {
removeTableRow()
};
body {
background: white;
}
img {
height: 100%;
display: block;
margin: 0 auto;
}
p {
text-align: center;
}
.container {
width: 100%;
max-width: 600px;
border-radius: 2px;
margin: 0 auto;
margin-top: 8vh;
background: lightgray;
box-shadow: 0px 4px 4px darkgray;
}
table {
width: 100%;
text-align: center;
}
td,
th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
/* Button */
.btn {
display: inline-block;
margin: 1em auto;
font-weight: 100;
padding: 1em 1.25em;
text-align: center;
width: 100%;
border-radius: 1px;
position: relative;
z-index: 0;
cursor: pointer;
border: none;
background: #0c84e4;
box-shadow: 0px 1px 1px #063e6b;
color: #FFFFFF;
}
:focus {
outline: -webkit-focus-ring-color auto 0px;
}
.btn.red {
background: red;
width: 100%;
}
/* input field style's */
input[type=text] {
width: calc(25% - 8px);
padding: 12px 20px 12px 5px;
margin: 8px 4px;
box-sizing: border-box;
float: left;
border: none;
border-bottom: 2px solid #536DFE;
text-align: center;
background: transparent;
}
input:focus {
outline: none;
color: black;
}
::-webkit-input-placeholder {
color: black;
font: helvetica 12px bold;
text-align: center;
}
select {
width: calc(25% - 8px);
padding: 12px 20px 12px 5px;
margin: 8px 4px;
box-sizing: border-box;
float: left;
border: none;
border-bottom: 2px solid #536DFE;
text-align: center;
background: transparent;
height: 39px;
border-radius: 0px !important;
}
<!DOCTYPE html>
<html>
<head>
<title>Inzend Opgave H5</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<!-- style sheets -->
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="wrapper">
<section class="container">
<form id="personInfo" name="myForm">
<table>
<thead>
<tr>
<td>nr.</td>
<td>First Name</td>
<td>Last Name</td>
<td>Age</td>
<td>Country</td>
</tr>
</thead>
<tbody id="table">
</tbody>
</table>
<input type="text" name="firstName" placeholder="firstName" id="firstName">
<input type="text" name="lastName" placeholder="lastName" id="lastName">
<input type="text" name="Age" placeholder="Age" id="age">
<select name="Country" id="country">
<option value="choose a country">Kies een land</option>
<option value="Nederland">NL</option>
<option value="Belgie">BE</option>
<option value="Duitsland">DE</option>
</select>
<input type="button" name="button" id="btn" class="btn" value="Add the input fields to the table">
<p>To remove a table number fill in the input field with the <br> number of the table and click remove table row</p>
<input type="button" name="button" id="removeRowBtn" class="btn" value="remove table row" style="width: 75%;">
<input type="text" name="TableNr" id="tableNr" placeholder="table nr.">
</form>
</section>
</div>
<!-- java-scripts -->
<script type="text/javascript" src="script.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.2.js"></script>
<script type="text/javascript">
var cw = $('.container').width();
$('.container').css({
'height': cw + 'px'
});
</script>
</body>
</html>

this is my solution i don't think it is the nicest way but it works, thanks for the help with thinking Inuka.
var btn = document.getElementById("btn");
var table = document.getElementById("table");
var removeRowBtn = document.getElementById("removeRowBtn");
// input fields Variable
var firstName = document.myForm.firstName;
var lastName = document.myForm.lastName;
var Age = document.myForm.Age;
var Country = document.myForm.Country;
var row = document.getElementById("table").getElementsByTagName("tr");
btn.onclick = function() {
addData()
};
// this function is checking if the input fields have the recuired data in it other wise it give's a error.
function validate() {
// first name field check + error
if (document.myForm.firstName.value == "") {
alert("Please provide your first name!");
document.myForm.firstName.focus();
return false;
}
// last name field check + error message
if (document.myForm.lastName.value == "") {
alert("Please provide your last name!");
document.myForm.lastName.focus();
return false;
}
// age field check + error message
if (isNaN(document.myForm.Age.value) || document.myForm.Age.value < 1 || document.myForm.Age.value > 100) {
alert("Please provide your age!");
return false;
}
// country select list check + error message
if (document.myForm.Country.value == "chooseCountry") {
alert("Please provide your country!");
return false;
}
// if evry thing is true return a value of true
return true;
}
function addData() {
if (validate()) {
// creating a new tr
var tr = document.createElement("tr");
// adding the created elements to a object with a class name
table.appendChild(tr);
var rows = " ";
rows += "<td>" + row.length + "</td><td>" + firstName.value + "</td><td>" + lastName.value + "</td><td>" + age.value + "</td><td>" + country.value + "</td>";
tr.innerHTML = rows;
//console.log(row.length, " 'row length' ");
//console.log(firstName.value, " 'firstname value' ");
//console.log(lastName.value, " 'lastName value' ");
//console.log(age.value, " 'age value' ");
//console.log(country.value, " 'country value' ");
}
}
function removeTableRow() {
var tableNr = document.getElementById("tableNr");
i = tableNr.value - 1;
// if there is no table number filled in show a error alert
if (i == "") {
alert("Please provide a table number!");
tableNr.focus();
return false;
}
// find the chosen array
var row = table.getElementsByTagName("tr")[i];
// if the number is not in the row show error alert that it issen't in the table
if (row == undefined) {
alert("this row number is not in the table");
return false;
}
// remove the selected row
row.remove(row.selectedIndex);
row = document.getElementById("table").getElementsByTagName("tr");
// rework the row length
for (var i = 0; i < row.length; i++) {
row[i].cells[0].innerText = i+1;
}
console.log("Row length: "+ row.length);
}
removeRowBtn.onclick = function() {
removeTableRow()
};
body{
background: white;
}
img{
height: 100%;
display: block;
margin: 0 auto;
}
p{
text-align: center;
}
.container{
width: 100%;
max-width: 600px;
border-radius: 2px;
margin: 0 auto;
margin-top: 8vh;
background: lightgray;
box-shadow: 0px 4px 4px darkgray;
}
table{
width: 100%;
text-align: center;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
/* Button */
.btn {
display: inline-block;
margin: 1em auto;
font-weight: 100;
padding: 1em 1.25em;
text-align: center;
width: 100% ;
border-radius: 1px;
position: relative;
z-index: 0;
cursor: pointer;
border: none;
background: #0c84e4;
box-shadow: 0px 1px 1px #063e6b;
color: #FFFFFF;
}
:focus {
outline: -webkit-focus-ring-color auto 0px;
}
.btn.red{
background:red;
width: 100%;
}
/* input field style's */
input[type=text] {
width: calc(25% - 8px);
padding: 12px 20px 12px 5px;
margin: 8px 4px;
box-sizing: border-box;
float: left;
border: none;
border-bottom: 2px solid #536DFE;
text-align: center;
background: transparent;
}
input:focus{
outline: none;
color: black;
}
::-webkit-input-placeholder{
color:black;
font: helvetica 12px bold ;
text-align: center;
}
select{
width: calc(25% - 8px);
padding: 12px 20px 12px 5px;
margin: 8px 4px;
box-sizing: border-box;
float: left;
border: none;
border-bottom: 2px solid #536DFE;
text-align: center;
background: transparent;
height: 39px;
border-radius: 0px !important;
}
<!DOCTYPE html>
<html>
<head>
<title>Inzend Opgave H5</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<!-- style sheets -->
<link href="style.css" rel="stylesheet" type="text/css" >
</head>
<body>
<div id="wrapper">
<section class="container">
<form id="personInfo" name="myForm">
<table>
<thead>
<tr>
<td>nr.</td>
<td>First Name</td>
<td>Last Name</td>
<td>Age</td>
<td>Country</td>
</tr>
</thead>
<tbody id="table">
</tbody>
</table>
<input type="text" name="firstName" placeholder="firstName" id="firstName">
<input type="text" name="lastName" placeholder="lastName" id="lastName">
<input type="text" name="Age" placeholder="Age" id="age">
<select name="Country" id="country">
<option value="choose a country">Kies een land</option>
<option value="Nederland">NL</option>
<option value="Belgie">BE</option>
<option value="Duitsland">DE</option>
</select>
<input type="button" name="button" id="btn" class="btn" value="Add the input fields to the table">
<p>To remove a table number fill in the input field with the <br> number of the table and click remove table row</p>
<input type="button" name="button" id="removeRowBtn" class="btn" value="remove table row" style="width: 75%;">
<input type="text" name="TableNr" id="tableNr" placeholder="table nr.">
</form>
</section>
</div>
<!-- java-scripts -->
<script type="text/javascript" src="script.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.2.js"></script>
<script type="text/javascript">
var cw = $('.container').width();
$('.container').css({
'height': cw + 'px'
});
</script>
</body>
</html>

Related

my innerHTML doesn't changes when i press the key

I wrote this code where the list item to be added stay in the top of the list, and the order should actualize the just like the variable, but it doens't change, it remains 1
window.addEventListener('keydown', addItem)
var order = 1;
var listItem = [""];
var listQuantity = [0];
var orderin = document.getElementById('order-register');
orderin.innerHTML = order;
function addItem() {
let itemout, qttout, addrow;
let table = document.getElementById('tabelaitens');
let itemin = document.getElementById('itemin');
let qttin = document.getElementById('qttin');
let key = event.key;
if (key == "Enter") {
if (itemin.value != "") {
itemout = itemin.value;
} else {
//add dropdown
}
if (qttin.value > 0) {
qttout = qttin.value;
} else {
//add dropdown
}
if ((itemout != undefined) && (qttout != undefined)) {
orderin.innerHTML = '' + order;
addrow = "<td class=\"order\">" + order + "</td><td class=\"item\">" + itemout + "</td><td class=\"quantity\">" + qttout + "</td>";
table.innerHTML += addrow;
order++;
orderin.innerHTML = order;
}
}
}
* {
margin: 0px;
padding: 0px;
box-sizing: border-box;
}
table,
tr,
td {
border-collapse: collapse;
}
#tabelaitens {
background-color: blanchedalmond;
width: 1000px;
margin: auto;
}
.linha,
.linharegister {
border-collapse: collapse;
}
.order {
width: 5%;
padding: 10px;
text-align: center;
}
.item {
width: 85%;
padding: 10px 5px;
}
.quantity {
width: 10%;
padding: 10px 5px;
}
#order-register {
text-align: center;
}
#order-register,
.item-register,
.quantity-register {
padding: 5px
}
.item-register>input,
.item-register>input:focus,
.quantity-register>input,
.quantity-register>input:focus {
width: 100%;
background-color: transparent;
border: none;
outline: none;
border-bottom: solid rgb(196, 183, 164);
}
.quantity-register>input {
text-align: center;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Lista de Compras</title>
<link rel="icon" href="img/list.png">
<link rel="stylesheet" href="styletable.css">
<script src="javascript/addlist.js" defer></script>
</head>
<body>
<main>
<ul>
<h1>
<li id="listname">lista</li>
</h1>
</ul>
<table id="tabelaitens">
<tr class="linha">
<td class="order">Ordem</td>
<td class="item">Item</td>
<td class="quantity">Quantidade</td>
</tr>
<tr class="linharegister">
<form>
<td id="order-register">PH</td>
<td class="item-register"><input id="itemin" type="text" name="itemregister" autocomplete="off"></td>
<td class="quantity-register"><input id="qttin" type="number" name="itemregister" autocomplete="off" min="1"></td>
</form>
</tr>
</table>
</main>
</body>
I tried make the var turn into a let, put the value in innerHTML outside the if, and a lot of small things that didn't changed anything at all. I dont know if it is an error in the syntax, logic or whatever, but one thing is right, there is no ";" missing.
You're creating invalid HTML because you don't have <tr> around the new row that you're adding. The browser is trying to fix it, but it ends up putting the added row at the beginning instead of the end. Add this and you get the desired result.
window.addEventListener('keydown', addItem)
var order = 1;
var listItem = [""];
var listQuantity = [0];
var orderin = document.getElementById('order-register');
orderin.innerHTML = order;
function addItem() {
let itemout, qttout, addrow;
let table = document.getElementById('tabelaitens');
let itemin = document.getElementById('itemin');
let qttin = document.getElementById('qttin');
let key = event.key;
if (key == "Enter") {
if (itemin.value != "") {
itemout = itemin.value;
} else {
//add dropdown
}
if (qttin.value > 0) {
qttout = qttin.value;
} else {
//add dropdown
}
if ((itemout != undefined) && (qttout != undefined)) {
addrow = "<tr><td class=\"order\">" + order + "</td><td class=\"item\">" + itemout + "</td><td class=\"quantity\">" + qttout + "</td><tr>";
table.innerHTML += addrow;
order++;
orderin.innerHTML = order;
}
}
}
* {
margin: 0px;
padding: 0px;
box-sizing: border-box;
}
table,
tr,
td {
border-collapse: collapse;
}
#tabelaitens {
background-color: blanchedalmond;
width: 1000px;
margin: auto;
}
.linha,
.linharegister {
border-collapse: collapse;
}
.order {
width: 5%;
padding: 10px;
text-align: center;
}
.item {
width: 85%;
padding: 10px 5px;
}
.quantity {
width: 10%;
padding: 10px 5px;
}
#order-register {
text-align: center;
}
#order-register,
.item-register,
.quantity-register {
padding: 5px
}
.item-register>input,
.item-register>input:focus,
.quantity-register>input,
.quantity-register>input:focus {
width: 100%;
background-color: transparent;
border: none;
outline: none;
border-bottom: solid rgb(196, 183, 164);
}
.quantity-register>input {
text-align: center;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Lista de Compras</title>
<link rel="icon" href="img/list.png">
<link rel="stylesheet" href="styletable.css">
<script src="javascript/addlist.js" defer></script>
</head>
<body>
<main>
<ul>
<h1>
<li id="listname">lista</li>
</h1>
</ul>
<table id="tabelaitens">
<tr class="linha">
<td class="order">Ordem</td>
<td class="item">Item</td>
<td class="quantity">Quantidade</td>
</tr>
<tr class="linharegister">
<form>
<td id="order-register">PH</td>
<td class="item-register"><input id="itemin" type="text" name="itemregister" autocomplete="off"></td>
<td class="quantity-register"><input id="qttin" type="number" name="itemregister" autocomplete="off" min="1"></td>
</form>
</tr>
</table>
</main>
</body>

how to load a json file with select option click

I'm trying to populate a table with JSON data file but that will happen when I choose an option from select options because each one of them refers to a different JSON data file, what happens is that only the Header of the table that showed beacuse it's already in the html part.
this what I get
this how it should look like
this how my code look like
$('#mySelect').change(function() {
if ($(this).val() === 'poly') {
$("#table").show();
get_json_data('poly.json');
}
else{
$("#table").show();
get_json_data('mono.json');
}
});
function get_json_data(json_url) {
// var json_url = 'example.json';
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var data = JSON.parse(this.responseText);
console.log(data);
append_json(data);
}
}
xmlhttp.open("POST", json_url, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send();
}
function append_json(data) {
var table = document.getElementById('gable');
data.forEach(function(object) {
var tr = document.createElement('tr');
tr.innerHTML =
'<td > <input type="radio" value ="' + object.RendementDuPanneau + '" name="choice" /> </td>' +
'<td>' + object.Fournisseur + '</td>' +
'<td>' + object.Modele + '</td>' +
'<td>' + object.PuissanceMaximale + '</td>' +
'<td>' + object.RendementDuPanneau + '</td>';
table.appendChild(tr);
});
var elements = document.getElementsByTagName('tr');
for (var i = 0; i < elements.length; i++) {
(elements)[i].addEventListener("click", function() {
const rb = this.querySelector('input[name="choice"]');
rb.checked = true;
let selectedValue = rb.value;
alert(selectedValue);
});
}
}
*, *:before, *:after {
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
body {
font-family: 'Nunito', sans-serif;
color: #384047;
}
form {
max-width: 400px;
margin: 10px auto;
padding: 10px 20px;
background: #f4f7f8;
border-radius: 8px;
}
select {
background: rgba(255,255,255,0.1);
border: none;
font-size: 16px;
height: auto;
margin: 0;
outline: 0;
padding: 15px;
width: 100%;
background-color: #e8eeef;
color: #202529;
box-shadow: 0 1px 0 rgba(0,0,0,0.03) inset;
margin-bottom: 30px;
}
legend {
font-size: 1.4em;
margin-bottom: 10px;
}
table {
border: 2px solid #ccc;
border-collapse: collapse;
margin: 0;
padding: 0;
width: 100%;
table-layout: fixed;
}
.my-custom-scrollbar {
position: relative;
height: 200px;
overflow: auto;
}
.table-wrapper-scroll-y {
display: block;
}
table thead th ,table tbody td
{
font-size : 12px;
}
tr:hover{
background-color:gray;
cursor:pointer;
}
table tbody td, table thead th {
text-align: center;
}
table tbody td:last-child, table thead th:last-child {
border-right: none;
}
table tbody td:first-child, table thead th:first-child {
width: 15px;
border-right: none;
}
table tbody td:nth-child(2), table thead th:nth-child(2) {
width: 100px;
border-left: none;
}
table tbody td:nth-child(3), table thead th:nth-child(3) {
width: 150px;
}
table tbody td:nth-child(4), table thead th:nth-child(4) {
width: 80px;
}
table tbody td:nth-child(5), table thead th:nth-child(5) {
width: 100px;
}
#media screen and (min-width: 480px) {
form {
max-width: 480px;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link href='https://fonts.googleapis.com/css?family=Nunito:400,300' rel='stylesheet' type='text/css'>
<form action="index.html" method="post" id="formName" name="calculeForm">
<div id="selecttype" >
<legend>Type de panneau : </legend>
<select id="mySelect" name="typeP" >
<optgroup label="Votre Type De Panneau"></optgroup>
<option></option>
<option value="poly">Silicium polycristallin</option>
<option value="mono">Silicium monocristallin</option>
</select>
</div> <br>
<div class="table-wrapper-scroll-y my-custom-scrollbar" id="table" style="display:none;">
<table class="table table-bordered table-striped mb-0" id="gable">
<thead>
<tr>
<th></th>
<th>Fournisseur</th>
<th>Modèle</th>
<th>Puissance maximale</th>
<th>Rendement du panneau</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</form>
this how my data look like
poly.json
[{"Fournisseur":"Jinko Solar","Modele":"JKM270PP-60","PuissanceMaximale":270,"RendementDuPanneau":"16,50"},{"Fournisseur":"Jinko Solar","Modele":"JKM275PP-60","PuissanceMaximale":275,"RendementDuPanneau":"16,80"},{"Fournisseur":"Jinko Solar","Modele":"JKM280PP-60","PuissanceMaximale":280,"RendementDuPanneau":"17,11"},{"Fournisseur":"Jinko Solar","Modele":"JKM285PP-60","PuissanceMaximale":285,"RendementDuPanneau":"17,41"},{"Fournisseur":"Jinko Solar","Modele":"JKM320PP-72","PuissanceMaximale":320,"RendementDuPanneau":"16,49"}]
mono.json
[{"Fournisseur":"Risen Energy","Modele":"RSM120-6-310P","PuissanceMaximale":310,"RendementDuPanneau":"18,40%"},{"Fournisseur":"Risen Energy","Modele":"RSM120-6-315P","PuissanceMaximale":315,"RendementDuPanneau":"18,70%"},{"Fournisseur":"Risen Energy","Modele":"RSM120-6-320P","PuissanceMaximale":320,"RendementDuPanneau":"19,00%"},{"Fournisseur":"Risen Energy","Modele":"RSM120-6-325P","PuissanceMaximale":325,"RendementDuPanneau":"19,30%"},{"Fournisseur":"Risen Energy","Modele":"RSM120-6-330P","PuissanceMaximale":330,"RendementDuPanneau":"19,60%"}]

How to find the problem in this HTML form that uses AJAX requests but fails with textarea

I am trying to receive customer feedback and transfer that data to Google Forms with AJAX requests, but my form keeps failing to work with textarea. How do I do this properly, since I am not sure where the problem lies.
[NOTE: The form works perfectly without textarea, but I figured I need textarea to receive a large user input, ex: descriptions of answers]
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="http://fonts.googleapis.com/css?family=Dosis|Ubuntu+Mono|Quicksand|Josefin+Sans|Montserrat|Francois+One|Marvel" rel="stylesheet" type="text/css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body style="background:white; font-family:Montserrat;">
<h1>Feedback/Review</h1>
<p>The Team would be happy to hear from you about our services! Leave feedback or a review using the form below.</p>
<form id="form" target="_self" onsubmit="return postToGoogle();" action="" autocomplete="off">
<label id = "namelabel">Name:</label><label id = "emaillabel">Email: </label><br>
<input id="nameField" name="entry.1803640717" placeholder="First / Last Name" type="text" required>
<input id="emailField" name="entry.63463603" placeholder="Enter Your Email" type="email" required><br><br>
<label id = "relationlabel">Relation:</label><label id = "choicelabel">Why are you contacting us?</label><br>
<input id="mobField" name="entry.1793553898" placeholder="Relation to [BUSINESS] (EX: customer)" type="text" required>
<select id="cinema" name="entry.26162353" placeholder="Select Cinema" required>
<option value="">Choose an Option</option>
<option value="">Question about Prices</option>
<option value="">Had Issues With The Process</option>
<option value="">Feedback for great work</option>
<option value="">Other Option/Not Listed</option>
</select><br><br>
<label>Comment Here:</label><br>
<textarea id="explainfield" name="entry.1396765295" rows = "10" cols = "128" required></textarea>
<button id="send" type="submit" class="common_btn">Submit Form</button>
</form>
<h3 id="success-msg" style="text-align: center !important; margin-top:190px !important; display:none; color:#fff"> Your Request has been recieved!</h3>
<style>
body {font-family: Arial, Helvetica, sans-serif; margin-left: 330px; margin-right: 330px;}
form {border: 3px solid #f1f1f1; font-family: QuickSand;}
input[type=text], input[type=email], select {
width: 49%;
font-size:20px;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
box-sizing: border-box;
}
button {
background-color: maroon;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 98.5%;
}
button:hover {
opacity: 0.4;
}
.cancelbtn {
width: auto;
padding: 10px 18px;
background-color: #f44336;
}
.imgcontainer {
text-align: center;
margin: 24px 0 12px 0;
}
img.avatar {
width: 20%;
border-radius: 50%;
}
.container {
padding: 16px;
}
span.psw {
float: right;
padding-top: 16px;
}
#namelabel, #relationlabel {
margin-right: 30px;
}
#emaillabel {
margin-left: 385px;
}
#choicelabel {
margin-left: 370px;
}
/* Change styles for span and cancel button on extra small screens */
#media screen and (max-width: 300px) {
span.psw {
display: block;
float: none;
}
.cancelbtn {
width: 100%;
}
}
</style>
<script>
function postToGoogle() {
var field1 = $("#nameField").val();
var field2 = $("#emailField").val();
var field3 = $("#mobField").val();
var field4 = $("#cinema option:selected").text();
var field5 = $("#explainfield").val();
if(field1 == ""){
alert('Please Fill Your Name');
document.getElementById("nameField").focus();
return false;
}
if(field2 == ""){
alert('Please Fill Your Email');
document.getElementById("emailField").focus();
return false;
}
if(field3 == "" || field3.length < 1){
alert('Please Fill Your Mobile Number');
document.getElementById("mobField").focus();
return false;
}
if (field5 == "" || field5.length < 1 {
alert('Please comment down below');
document.getElementById("explainfield").focus();
return false;
}
$.ajax({
url: "https://docs.google.com/forms/d/e/1FAIpQLSdTNZewdXbyY51ueD9OEBi4Cca3JkVT1p4CykMSPyfzRpWHyQ/formResponse?",
data: {"entry.1803640717": field1, "entry.63463603": field2, "entry.1793553898": field3, "entry.26162353": field4, "entry.1396765295": field5},
type: "POST",
dataType: "xml",
success: function(d)
{
},
error: function(x, y, z)
{
$('#success-msg').show();
$('#form').hide();
}
});
return false;
}
</script>
</body>
</html>
I don't know if it will solve your problem but you have forgotten a closing bracket :
if (field5 == "" || field5.length < 1 {
should be
if (field5 == "" || field5.length < 1) {

Select the rows from the table by clicking a button and update the values

I am trying to create an edit button so that when it's clicked, it selects the entire row and fills the inputs above with the values from it for modifications or updates. I can't seem to make my code work for more than 3 rows because it gets stuck somewhere. In my code below, the modify button doesn't show any errors in the console so I can't figure out what I did wrong.
I'm trying to create a phone book using a dynamic table that needs to have 2 buttons, one named modify and one named delete. The problem is the modify button which doesn't seem to work. Thank you in advance.
var clientList = [{
name: "Nume1",
lastName: "Prenume1",
phone: ["0758066000"],
initialOrder: 1
},
{
name: "Nume3",
lastName: "Prenume3",
phone: ["0758000000"],
initialOrder: 2
},
{
name: "Nume2",
lastName: "Prenume2",
phone: ["0758000000", "0758000000"],
initialOrder: 3
},
{
name: "Nume4",
lastName: "Prenume4",
phone: ["075803481"],
initialOrder: 4
},
{
name: "Nume5",
lastName: "Prenume5",
phone: ["07942990220"],
initialOrder: 5
}
];
//drawing the table
function showDataInTable(arr) {
var tableBody = document.getElementById('tableBody');
var tableData = "";
for (var i = 0; i < arr.length; i++) {
tableData += `
<tr>
<td>${clientList[i].name}</td>
<td>${clientList[i].lastName}</td>
<td>${clientList[i].phone}</td>
<td data-index ="${i}" data-id ="modify" class="buttons1">modify</td>
<td data-index ="${i}" data-id ="delete" class="buttons2">delete</td>
<tr>
`;
}
tableBody.innerHTML = tableData;
}
showDataInTable(clientList);
//writing the sorting function
function sort(arr, parameter, sortDirection) {
for (var i = 0; i < arr.length; i++) {
for (var j = i + 1; j < arr.length; j++) {
if (sortDirection === "up") {
if (arr[i][parameter] > arr[j][parameter]) {
var temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
} else if (sortDirection === "down") {
if (arr[i][parameter] < arr[j][parameter]) {
var temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
showDataInTable(arr);
}
//table click event
document.getElementById("table").addEventListener("click", tableClicked);
var sortDirection;
var index;
var editingTable;
function tableClicked() {
//table delete
function delClient(arr, index) {
arr.splice(index, 1);
}
index = Number(event.target.parentElement.rowIndex - 1);
if (event.currentTarget.dataset.id == "delete") {
delClient(clientList, index);
showDataInTable(clientList);
}
// table edit
if (event.currentTarget.dataset.id == "modify") {
document.getElementById("nameInput").delete = clientList[index].name;
document.getElementById("lastNameInput").value = clientList[index].lastName;
document.getElementById("phoneInput").value = clientList[index].phone;
document.getElementById("submit").value = "SAVE";
}
//table sorting
if (event.target.tagName == "TH") {
var headers = document.getElementsByTagName("th");
for (var i = 0; i < headers.length; i++) {
headers[i].classList.remove("selected");
}
event.target.classList.add("selected");
if (sortDirection == "up") sortDirection = "down";
else sortDirection = "up";
var parameter = event.target.id;
sort(clientList, parameter, sortDirection);
}
}
// when form is clicked
document.getElementById("myForm").addEventListener("click", formClicked);
function formClicked() {
//add client or edit existing
if (event.target.id == "submit") {
event.preventDefault();
var name = document.getElementById("nameInput").value;
var lastName = document.getElementById("lastNameInput").value;
var phone = document.getElementById("phoneInput").value;
phone = phone.split(",");
if (name && lastName && phone) {
if (editingTable == true) {
clientList[index].name = name;
clientList[index].lastName = lastName;
clientList[index].phone = phone;
document.getElementById("submit").value = "ADD CONTACT";
editingTable = false;
} else {
var newClient = {
name: name,
lastName: lastName,
phone: phone
}
clientList.push(newClient);
}
//redraw the table
showDataInTable(clientList);
//reset input fields
document.getElementById("nameInput").value = "";
document.getElementById("lastNameInput").value = "";
document.getElementById("phoneInput").value = "";
} else {
alert("INPUT FIELDS ARE INCOMPLETE!");
}
}
}
//make sure phoneInput gets numbers
document.getElementById("phoneInput").addEventListener("keydown", checkInput);
document.getElementById("phoneInput").addEventListener("input", checkInput);
function checkInput() {
if (/[^0-9]/.test(event.key) && event.keyCode !== 8) {
event.preventDefault();
}
}
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
#header {
font-family: 'Press Start 2P', cursive;
font-size: 40px;
color: dodgerblue;
margin-top: 30px;
}
body {
text-align: center;
}
p {
margin-bottom: 10px;
}
form {
border: 1px solid lightgray;
padding: 10px;
display: flex;
flex-flow: row wrap;
align-items: center;
-webkit-box-shadow: 10px 10px 15px -1px rgba(59, 89, 152, 0.85);
-moz-box-shadow: 10px 10px 15px -1px rgba(59, 89, 152, 0.85);
box-shadow: 10px 10px 15px -1px rgba(59, 89, 152, 0.85);
}
.input {
margin-left: 300px;
margin-right: 300px;
margin-top: 20px;
}
#name {
margin: 5px 10px 5px 0;
}
#lastName {
margin: 5px 10px 5px 0;
}
#phone {
margin: 5px 10px 5px 0;
}
input {
vertical-align: middle;
margin: 5px 10px 5px 0;
padding: 10px;
background-color: #fff;
border: 1px solid grey;
width: 250px;
}
#submit {
background-color: dodgerblue;
border: 1px solid #ddd;
color: white;
}
#submit:hover {
background-color: lightblue;
color: black;
}
table {
border-collapse: collapse;
width: 69%;
margin-top: 50px;
margin-left: auto;
margin-right: auto;
-webkit-box-shadow: 10px 10px 15px -1px rgba(59, 89, 152, 0.85);
-moz-box-shadow: 10px 10px 15px -1px rgba(59, 89, 152, 0.85);
box-shadow: 10px 10px 15px -1px rgba(59, 89, 152, 0.85);
}
td {
padding: 5px;
cursor: pointer;
border-bottom: 1px solid lightgrey;
font-size: 20px;
border-left: 1px solid grey;
}
th {
padding: 5px;
font-size: 25px;
background-color: dodgerblue;
color: white;
font-weight: 100;
cursor: pointer;
}
#media (max-width: 800px) {
input {
margin: 10px 0;
}
form {
flex-direction: column;
align-items: stretch;
}
}
.selected {
background-color: lightskyblue;
border: 3px solid white;
color: black;
}
.buttons1:hover {
background-color: lightgreen;
}
.buttons2:hover {
background-color: lightcoral;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="description" content="Agenda telefonica">
<meta name="author" content="Adelina Lipsa">
<meta name="keywords" content="HTML,CSS,JavaScript">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Agenda telefonica</title>
<link href="stylesheet.css" rel="stylesheet" type="text/css">
<script src="javascript.js" defer></script>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/solid.css" integrity="sha384-ioUrHig76ITq4aEJ67dHzTvqjsAP/7IzgwE7lgJcg2r7BRNGYSK0LwSmROzYtgzs" crossorigin="anonymous">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/fontawesome.css" integrity="sha384-sri+NftO+0hcisDKgr287Y/1LVnInHJ1l+XC7+FOabmTTIK0HnE2ID+xxvJ21c5J" crossorigin="anonymous">
<link href="https://fonts.googleapis.com/css?family=Press+Start+2P&display=swap" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<h1 id="header"><i class="fas fa-phone-square"></i> Phone book</h1>
<div id="wrapper">
<div class="input">
<form id="myForm">
<p>Nume:</p>
<input type="text" id="nameInput">
<p>Prenume:</p>
<input type="text" id="lastNameInput">
<p>Telefon:</p>
<input type="text" id="phoneInput">
<input type="submit" id="submit" value="ADD CONTACT">
</form>
</div>
<div>
<table id="table">
<thead id="thead">
<tr>
<th id="name">Nume <i class="fas fa-sort"></i></th>
<th id="lastName">Prenume <i class="fas fa-sort"></i></th>
<th id="phone">Telefon <i class="fas fa-sort"></i></th>
<th colspan="2"></th>
</tr>
</thead>
<tbody id="tableBody"></tbody>
</table>
</div>
</div>
</body>
</html>
There are some issues in your code.
You need to use target rather than currentTarget because you want to get the element the user clicked on (the button) but not the one you listen to (the table). [1]
document.getElementById("nameInput").delete should be document.getElementById("nameInput").value.
In showDataInTable You need to close the tr tag (</tr>) instead of open one (<tr>)
https://jsbin.com/taqaqor/edit?js,output
[1] The currentTarget read-only property of the Event interface identifies the current target for the event, as the event traverses the DOM. It always refers to the element to which the event handler has been attached, as opposed to Event.target, which identifies the element on which the event occurred and which may be its direct descendent.
https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget
The biggest problem is that you're switching event.target and event.currentTarget around.
Since you bind the click event to the table, the event.currentTarget equals the table, not the table cell. And the event.target is actually the table cell.
But your code expects if (event.currentTarget.dataset.id == "delete") and if (event.currentTarget.dataset.id == "modify"), whcih will always be undefined, since the data attributes are on the cell, not the table.
You would expect this to throw an error, but since both target and currentTarget exist, it does not throw.
If I change event.currentTarget() into event.target(), I can delete and modify all the rows. There's still some other issues ( like delete deleting the last element instead of the clicked one ), but that does solve the main question.

Clickable grid with each <td> changing colors using onclick method

So I'm just learning how to make a clickable grid using Jquery and I have difficulty in finding how to make each block to change colors on click. I was attempting to add a class to each through the addClass method. My main difficulty is to find each to incorporate an onclick or changeColor method.
$('body').on('click', 'td', changeColor());
function generateGrid(rows, cols) {
var grid = "<table>";
for (row = 1; row <= rows; row++) {
grid += "<tr>";
for (col = 1; col <= cols; col++) {
var cell = "<td> </td>";
grid += cell;
}
grid += "</tr>";
}
$("#tableContainer").empty();
$("#tableContainer").append(grid);
return grid;
}
function changeColor() {
this.addClass("clicked");
}
body {
background-color: whitesmoke;
}
#tableContainer {
display: table;
padding: 1px;
margin-right: auto;
margin-left: auto;
}
td {
border: 1px solid;
width: 50px;
height: 50px;
padding: .5px;
background-color: skyblue;
display: table-cell;
align-items: center;
cursor: pointer;
}
td:hover {
display: block;
width: 100%;
background-color: grey;
}
.clicked {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<link rel="stylesheet" href="a3.css">
<script src="a3.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<body>
<!-- <input type = "button" id="bClick" onclick="myFunction()"> -->
Rows: <input type="number" name="Rows" id="Rows"><br> Columns: <input type="number" name="Columns" id="Columns"><br> Mines: <input type="number" name="mines"> <br><br>
<button onclick="generateGrid(document.getElementById('Rows').value, document.getElementById('Columns').value)"> Click for Grid </button>
<div id="tableContainer"></div>
</body>
</html>
You are executing the function you're passing as the event handler argument so remove the ().
$(document.body).on('click', 'td', changeColor);
Then you will be able to use this in the handler.
function changeColor() {
const $this = $(this);
if ($this.hasClass("clicked")) {
$this.removeClass("clicked")
} else {
$this.addClass("clicked");
}
}
$(document.body).on('click', 'td', changeColor);
function generateGrid(rows, cols) {
var grid = "<table>";
for (row = 1; row <= rows; row++) {
grid += "<tr>";
for (col = 1; col <= cols; col++) {
var cell = "<td> </td>";
grid += cell;
}
grid += "</tr>";
}
$("#tableContainer").empty();
$("#tableContainer").append(grid);
return grid;
}
function changeColor() {
const $this = $(this);
if ($this.hasClass("clicked")) {
$this.removeClass("clicked")
} else {
$this.addClass("clicked");
}
}
body {
background-color: whitesmoke;
}
#tableContainer {
display: table;
padding: 1px;
margin-right: auto;
margin-left: auto;
}
td {
border: 1px solid;
width: 50px;
height: 50px;
padding: .5px;
background-color: skyblue;
display: table-cell;
align-items: center;
cursor: pointer;
}
td:hover {
display: block;
width: 100%;
background-color: grey;
}
.clicked {
background-color: red;
}
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="a3.css">
<script src="a3.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
</head>
<body>
<!-- <input type = "button" id="bClick" onclick="myFunction()"> -->
Rows: <input type="number" name="Rows" id="Rows"><br> Columns: <input type="number" name="Columns" id="Columns"><br> Mines: <input type="number" name="mines"> <br><br>
<button onclick="generateGrid(document.getElementById('Rows').value, document.getElementById('Columns').value)"> Click for Grid </button>
<div id="tableContainer"></div>
</body>
</html>
Your issue here is that you are binding the click event on the td before they are ever on the page. You need to make sure to bind the click function at the bottom of your generateGrid() function, like so:
function generateGrid(rows, cols) {
var grid = "<table>";
for (row = 1; row <= rows; row++) {
grid += "<tr>";
for (col = 1; col <= cols; col++) {
var cell = "<td> </td>";
grid += cell;
}
grid += "</tr>";
}
$("#tableContainer").empty();
$("#tableContainer").append(grid);
$('td').click(function(){
changeColor($(this));
});
}
function changeColor(cell) {
if(cell.hasClass('clicked')){
cell.removeClass('clicked');
} else {
cell.addClass('clicked');
}
}
body {
background-color: whitesmoke;
}
#tableContainer {
display: table;
padding: 1px;
margin-right: auto;
margin-left: auto;
}
td {
border: 1px solid;
width: 50px;
height: 50px;
padding: .5px;
background-color: skyblue;
display: table-cell;
align-items: center;
cursor: pointer;
}
td:hover {
display: block;
width: 100%;
background-color: grey;
}
td.clicked {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<link rel="stylesheet" href="a3.css">
<script src="a3.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<body>
<!-- <input type = "button" id="bClick" onclick="myFunction()"> -->
Rows: <input type="number" name="Rows" id="Rows"><br> Columns: <input type="number" name="Columns" id="Columns"><br> Mines: <input type="number" name="mines"> <br><br>
<button onclick="generateGrid(document.getElementById('Rows').value, document.getElementById('Columns').value)"> Click for Grid </button>
<div id="tableContainer"></div>
</body>
</html>

Categories

Resources