my innerHTML doesn't changes when i press the key - javascript

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>

Related

How can I add strikethrough property by clicking the button next to the element?

I am new to coding, and I am trying to make a shopping list app although I ran into some problem.
I am trying to select the elements of a table, it has two columns one for the shopping item and one for buttons next to each item. I want to click the button next to the item and with that add a css style of strikethrough but only for that respective item. But now i can click any "Mark as buyed button" and will apply the styles for all the items, and after that sort the items in ascending or descending order with two other buttons. A little help/hint would be appreciated.
Thank you in advance, if my post is not that clear please do tell
Here is my code:
My code
let addItem = document.querySelector('.add-item');
let input = document.querySelector('input[type="text"]');
let table = document.querySelector('.list');
let tbody = document.querySelector('.tbody');
let ascBtn = document.querySelector('.btn-asc');
let descBtn = document.querySelector('.btn-desc');
// let itemsToSort = document.querySelector('.shopping-list-item');
// let shoppingItems = [];
addItem.addEventListener('click', addItemToList);
// ascBtn.addEventListener('click', ascend);
// descBtn.addEventListener('click', descend);
function addItemToList() {
if (input.value !== '') {
let tableRow = document.createElement('tr');
let firstTableData = document.createElement('td');
let secondTableData = document.createElement('td');
let actionBtn = document.createElement('button');
actionBtn.className = 'action-btn btn';
actionBtn.innerText = 'Mark as buyed';
firstTableData.className = 'shopping-list-item';
tbody.appendChild(tableRow);
firstTableData.innerHTML = input.value;
tableRow.appendChild(firstTableData);
secondTableData.appendChild(actionBtn)
tableRow.appendChild(secondTableData);
input.value = '';
// console.log(firstTableData, secondTableData)
// shoppingItems.push(input.value);
}
}
input.addEventListener('keydown', keyPress);
function keyPress(e) {
if (input.value !== '' && e.keyCode == 13) {
let tableRow = document.createElement('tr');
let firstTableData = document.createElement('td');
let secondTableData = document.createElement('td');
let actionBtn = document.createElement('button');
actionBtn.className = 'action-btn btn';
actionBtn.innerText = 'Mark as buyed';
firstTableData.className = 'shopping-list-item';
tbody.appendChild(tableRow);
firstTableData.innerHTML = input.value;
tableRow.appendChild(firstTableData);
secondTableData.appendChild(actionBtn)
tableRow.appendChild(secondTableData);
input.value = '';
}
}
table.addEventListener('click', function (e) {
// console.log(e.target)
// console.log('this works')
let dynamicTd = document.querySelectorAll('.shopping-list-item');
if (e.target && e.target.className == 'action-btn btn') {
// console.log('this works too');
for (let i = 0; i < dynamicTd.length; i++) {
console.log(dynamicTd[i]);
dynamicTd[i].className = 'checked';
}
}
})
// function ascend(a, b) {
// let item = shoppingItems.value;
// console.log(item);
// }
// function descend() {
// }
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: Verdana, Geneva, Tahoma, sans-serif;
color: #6c757d;
}
.shopping-list {
width: 1000px;
margin: 0 auto;
background-color: #2a9d8f;
margin-top: 50px;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
border-radius: 5px;
}
.btn {
display: inline-block;
}
.header {
text-align: center;
font-size: 60px;
font-weight: 200;
background-color: #f9f9f9;
width: 100%;
padding: 20px 0;
}
.form {
width: 500px;
padding: 30px 0;
}
.form input {
width: 60%;
padding: 10px 15px;
border-radius: 5px;
outline: none;
}
.form button {
width: 30%;
padding: 10px 10px;
margin-left: 20px;
border-radius: 5px;
outline: none;
}
.btn-container {
width: 50%;
}
.btn-container .btn {
width: 30%;
padding: 10px;
border-radius: 5px;
outline: none;
}
.list {
background-color: #a8dadc;
width: 50%;
margin-top: 20px;
border-radius: 5px;
padding: 10px 20px;
}
.list th {
padding: 10px 0;
}
.list td {
width: 60%;
}
.action-btn {
width: 100%;
padding: 10px;
border-radius: 5px;
outline: none;
}
.checked {
text-decoration: line-through;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Shopping List</title>
</head>
<body>
<section class="shopping-list">
<h2 class="header">Shopping List</h2>
<!-- prevent from submitting and disappearing of items add onsubmit -->
<form class="form" onsubmit="return false">
<input type="text">
<!-- prevent from submitting and disappearing of items add type='button' -->
<button type="button" class="add-item btn">Add Item</button>
</form>
<div class="btn-container">
<button class="btn-asc btn">Sort asc</button>
<button class="btn-desc btn">Sort desc</button>
</div>
<table class="list">
<thead>
<tr>
<th>Item</th>
<th>Action</th>
</tr>
</thead>
<tbody class="tbody">
</tbody>
</table>
</section>
<script src="app.js"></script>
</body>
</html>
You can traverse up the DOM using Node.parentNode before selecting the td using querySelector to apply the checked class.
table.addEventListener("click", function (e) {
if (e.target && e.target.className == "action-btn btn") {
const td = e.target.parentNode.parentNode.querySelector("td")
if (td) {
td.className = "checked";
}
}
});
Codepen
You can replace your for loop within method added to table as click listener to: e.target.parentElement.previousSibling.className = 'checked'.
But it is not the best solution. A better way to do this would be to store list items as objects in an array and add the dataset to the delete button. Then you can simply remove that array element based on dataset attribute.

eval() function not working in the calculator project

I am trying to finish a calculator project. I have successfully designed the HTML and CSS of the calculator, but facing issues in my JavaScript code. The ERROR coming is:
Uncaught SyntaxError: Invalid left-hand side in assignment
at HTMLButtonElement.addOutput (logic.js:13)
How to sort out the problem? Can anybody help on this?
I have added the complete project code. But the error is mainly in javascript.
The code:
JAVASCRIPT
let screen = document.getElementById('screen');
let buttons = document.querySelectorAll('button');
function addOutput(e) {
console.log(e.target.innerText);
let char = e.target.innerText;
msg =screen.value += char
if( char=='C'){
screen.value=" ";
}
else if(char=='=')
{
screen.value = eval(msg)
}
else{
msg="";
}
}
for (item of buttons){
item.addEventListener('click', addOutput);
}
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Calculator</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<div class="screen_style">
<h1>Calculator</h1>
</div>
<div class="calculator">
<input type="text" name="screen" id="screen">
<table>
<tr>
<td><button>(</button></td>
<td><button>)</button></td>
<td><button>C</button></td>
<td><button>%</button></td>
</tr>
<tr>
<td><button>7</button></td>
<td><button>8</button></td>
<td><button>9</button></td>
<td><button>x</button></td>
</tr>
<tr>
<td><button>4</button></td>
<td><button>5</button></td>
<td><button>6</button></td>
<td><button>-</button></td>
</tr>
<tr>
<td><button>1</button></td>
<td><button>2</button></td>
<td><button>3</button></td>
<td><button>+</button></td>
</tr>
<tr>
<td><button>0</button></td>
<td><button>.</button></td>
<td><button>/</button></td>
<td><button>=</button></td>
</tr>
</table>
</div>
</div>
</body>
<script src="logic.js"></script>
</html>
CSS:
.screen_style{
background-color: rgb(135, 222, 208);
width: 31%;
border: 1px solid white;
margin: auto;
border-radius: 20px;
}
.container{
text-align: center;
}
table{
margin: auto;
}
input{
font-size: 34px;
border: 4px solid brown;
border-radius: 21px;
margin: auto;
}
button{
font-size: 23px;
width: 90px;
height: 75px;
border-radius: 20px;
}
button:hover{
background-color: rgb(109, 128, 0);
}
.calculator{
background-color: khaki;
display: inline-block;
border-radius: 21px;
padding: 23px;
}
You are using += which is Addition Assignment. So this line,
msg = screen.value += char
means
msg = screen.value = screen.value + char
Which is invalid.
You need to just use a + to concatenate the char to screen.value.
UPDATE
You were adding a = at the end of screen.value which caused eval to throw error. You need to check if the char is a = before concatenating it to screen.value.
let screen = document.getElementById('screen');
let buttons = document.querySelectorAll('button');
function addOutput(e) {
let char = e.target.innerText;
screen.value += ["=", "C"].includes(char) ? "": char
msg = screen.value
if (char == 'C') {
screen.value = " ";
} else if (char == '=') {
screen.value = eval(msg)
} else {
msg = "";
}
}
for (item of buttons) {
item.addEventListener('click', addOutput);
}
.screen_style {
background-color: rgb(135, 222, 208);
width: 31%;
border: 1px solid white;
margin: auto;
border-radius: 20px;
}
.container {
text-align: center;
}
table {
margin: auto;
}
input {
font-size: 34px;
border: 4px solid brown;
border-radius: 21px;
margin: auto;
}
button {
font-size: 23px;
width: 90px;
height: 75px;
border-radius: 20px;
}
button:hover {
background-color: rgb(109, 128, 0);
}
.calculator {
background-color: khaki;
display: inline-block;
border-radius: 21px;
padding: 23px;
}
<!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>Calculator</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<div class="screen_style">
<h1>Calculator</h1>
</div>
<div class="calculator">
<input type="text" name="screen" id="screen">
<table>
<tr>
<td><button>(</button></td>
<td><button>)</button></td>
<td><button>C</button></td>
<td><button>%</button></td>
</tr>
<tr>
<td><button>7</button></td>
<td><button>8</button></td>
<td><button>9</button></td>
<td><button>x</button></td>
</tr>
<tr>
<td><button>4</button></td>
<td><button>5</button></td>
<td><button>6</button></td>
<td><button>-</button></td>
</tr>
<tr>
<td><button>1</button></td>
<td><button>2</button></td>
<td><button>3</button></td>
<td><button>+</button></td>
</tr>
<tr>
<td><button>0</button></td>
<td><button>.</button></td>
<td><button>/</button></td>
<td><button>=</button></td>
</tr>
</table>
</div>
</div>
</body>
<script src="logic.js"></script>
</html>
msg =screen.value += char
I believe you are trying to add char to screen.value, in which case the += should just be +
EDIT: You are adding the char to screen.value before the eval function is called (i.e. eval is getting "5+3=" instead of "5+5".
Updated JavaScript
let screen = document.getElementById('screen');
let buttons = document.querySelectorAll('button');
function addOutput(e) {
console.log(e.target.innerText);
let char = e.target.innerText;
console.log(screen.value)
if( char=='C'){
screen.value=" ";
}
else if(char=='=')
{
screen.value = eval(screen.value)
}
else{
screen.value += char
}
}
for (item of buttons){
item.addEventListener('click', addOutput);
}

Array and table

I created a table derived from an array, but I don't understand how to create a function that will overwrite an object in my array when editing on the page. You can run the worker code.
There was an idea to give all the cells id by their key and then somehow create a function for editing them, but I can't do it. :(
window.onload = function() {
document.querySelector('.bottom_panel > .plus').addEventListener('click', plusRow);
document.querySelector('.bottom_panel > .minus').addEventListener('click', minusRow);
document.querySelector('.right_panel > .plus').addEventListener('click', plusСolumn);
document.querySelector('.right_panel > .minus').addEventListener('click', minusСolumn);
// document.querySelectorAll('td > #0_0').addEventListener('oninput', alert);
const tbody = document.querySelector("tbody")
// function alert() {
// alert("11")
// }
array = [
[1,2,3,4],
[5,6,7,8],
[9,10,11,12],
[13,14,15,16]
];
let N = ''
let amountRow = array.length
newRow = []
let amountСolumn = array[0].length
console.log(amountСolumn)
function tableBuilder() {
tbody.textContent = ""
for (i = 0; i < array.length; i++) {
var tr = document.createElement('tr')
for (j = 0; j < array[i].length; j++) {
var td = document.createElement('td')
td.innerHTML = `<input id="` + i + `_` + j + `" type="text" value="` + array[i][j] + `">`
tr.appendChild(td)
}
tbody.appendChild(tr)
}
}
tableBuilder()
function plusRow() {
for (i = 0; i < array[0].length; i++) {
newRow.push('')
console.log(newRow)
}
array.push(newRow)
amountRow = array.length
console.log(array)
newRow = []
tableBuilder()
}
function minusRow() {
if (amountRow > 1) {
array.pop()
amountRow = array.length
console.log(amountRow)
} else {
alert("Nope!")
}
tableBuilder()
}
function plusСolumn() {
for ( i = 0; i < array.length; i++) {
array[i].push(N)
}
console.log(array)
amountСolumn = array[0].length
tableBuilder()
}
function minusСolumn() {
if (amountСolumn > 1) {
for ( i = 0; i < array.length; i++) {
array[i].pop()
}
amountСolumn = array[0].length
tableBuilder()
} else {
alert("Nope!")
}
}
}
// for (i = 0; i < array[0].length; i++) {
// rowNumber = array[i]
// for (k = 0; k < rowNumber.length; k++)
// point = rowNumber[k]
// console.log(rowNumber[k])
// tbody.innerHTML += `<div>` + point + `</div>`
// }
body {
display: flex;
justify-content: center;
margin: 20vh 0 0 0;
}
table {
border-collapse: collapse;
}
td {
text-align: center;
width: 100px;
height: 35px;
border: black 1px solid;
}
td:hover, input:hover {
cursor: pointer;
background: silver;
}
td:hover input {
cursor: pointer;
background: silver;
}
input {
margin: 1px 0 0 0;
border: none;
width: 90%;
height: 90%;
}
input:focus {
border: 1px #000 solid;
outline:none;
background: none !important;
}
button {
cursor: pointer;
width: 35px;
height: 20px;
}
.minus {
margin: 0 0 0 10px;
}
.bottom_panel {
display: flex;
justify-content: center;
margin: 20px 0 0 0;
}
.right_panel {
display: flex;
justify-content: center;
align-items: center;
margin: -3% 0 0 20px;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link href="style.css" rel="stylesheet">
<title>Spreadsheet</title>
<script src="script.js"></script>
</head>
<body>
<div class="table">
<table>
<tbody>
</tbody>
</table>
<div class="bottom_panel">
<button class="plus">+</button>
<button class="minus">-</button>
</div>
</div>
<div class="right_panel">
<button class="plus">+</button>
<button class="minus">-</button>
</div>
<script src="script.js"></script>
</body>
</html>
<!--<tr>-->
<!-- <td><input class="input" type="text" value="1" readonly="true" ondblclick="this.readOnly='';"></td>-->
<!-- <td><input type="text" value="2"></td>-->
<!-- <td><input class="input" type="text" value="3"></td>-->
<!--</tr>-->

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>

js row length needs to reset after row removal

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>

Categories

Resources