How to change class of specified <td>? - javascript

function change() {
var tds = document.getElementsByTagName("td");
var tds2 = tds.className;
console.log(tds);
for (var i = 0; i < tds.length; i++) {
if (tds[i].className === "marked") {
tds[i].className = "UNmarked";
} else {
tds[i].className = "marked";
}
}
}
function generTab(rows, cols) {
var html = "<table id='tb01'>";
for (var i = 1; i <= rows; i++) {
html += "<tr>"
for (var j = 1; j <= cols; j++) {
html += "<td class='marked' onclick='change()'>" + "</td>";
}
html += "</tr>"
}
return html + "</table>";
}
td.marked {
height: 50px;
width: 50px;
border: solid thin black;
cursor: pointer;
background-color: white;
}
td.UNmarked {
height: 50px;
width: 50px;
border: solid thin black;
cursor: pointer;
background-color: purple;
}
<div class="line">
Number of rows:
<input type="text" id="rows" />
</div>
<div class="line">
Number of cols:
<input type="text" id="cols" />
<span class="error"></span>
</div>
<input type="button" value="Generuj" id="gener" />
</div>
<div id="scene"></div>
I'm generating table by my own, and I want to change class of specified <td> by clicking on on it. The problem is that when I click on whichever <td> it is changing the classes of all of them, but I want to change that <td> class which I click.

May be you can do some thing like the following with a single class:
var tds = document.querySelectorAll("td");
tds.forEach(function(td){
td.addEventListener('click', function(){
this.classList.toggle('marked')
});
});
td {
border: 1px solid lightgray;
padding: 10px;
font-size: 20px;
}
.marked{
background-color: #4CAF50;
color: white;
}
<table>
<tr>
<td>1</td><td>2</td><td>3</td>
</tr>
<tr>
<td>4</td><td>5</td><td>6</td>
</tr>
</table>

Add click event listeners to all the td elements and implement a simple onClick function which adds/removes the desired css class.
const tds = Array.from(document.querySelectorAll('td'));
const onClick = ({ target }) => {
tds.forEach(td => td === target ? td.classList.add('active') : td.classList.remove('active'))
}
tds.forEach(td => td.addEventListener('click', onClick));
.active {
color: red;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
</head>
<body>
<table style="width:100%">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>
</body>
</html>

The code you've written should be toggling the class of all tds in the document. I believe you're trying to change the class of the td that is being clicked. To do that, try something like (apologies in advance as I'm on my phone):
function change(e) {
let td = e.target;
if (td.classList.contains('marked')) {
td.className = 'UNmarked';
} else {
td.className = 'marked';
}
}
and be sure that that change is bound as the click event for each td.

If you can use jQuery...
$("td").click(function(){
$(this).toggleClass("marked")
.toggleClass("UNmarked");
});

Related

JavaScript DOM table manipulation

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

javascript prompt not showing

I am trying to create some code for a class that prompts the user to input three numbers then preforms some calculations to those numbers, the math is to square one number, multiply and multiply the number by PI then display them in the appropriate cells. Right now my onClick is not working and there is no prompt coming up for the user. I have the min and max functions in there so because it's required
Here is my code:
function promptForNumber(promptString, min, max) {
Array.prototype.max = function() {
return Math.max.apply(null, this);
};
Array.prototype.min = function() {
return Math.min.apply(null, this);
};
}
function populateRow(row) {
var number = promptForNumber("Enter your number");
row.cells[0].innerHTML = number;
row.cells[1].innerHTML = Math.pow(number, 2);
row.cells[2].innerHTML = (number / Math.PI).toFixed(4);
}
function isNotANumber(NaN) {
var isNotANumer = promptForAValidNumber("Please enter a
valid number ")
}
table,
th,
tr,
td {
border-collapse: collapse;
}
table {
width: 80%;
margin: 10%;
}
th {
width: 33%;
border: 2px solid black;
justify-content: space-evenly;
height: 25px;
background-color: white;
}
td {
border: 1px solid black;
padding: 1%;
text-align: center;
background-color: greenyellow;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Assignment 2</title>
</head>
<body>
<table>
<tr>
<th>Number</th>
<th>Squared</th>
<th>Divided by Pi</th>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
</body>
</html>
This looks like a homework question as you mentioned it's for a class, so I cannot give you the exact solution to the problem. However, I will point out what is wrong with your code at the moment.
You mentioned that your "onClick" is not working, but you do not have any onClick functions in this code.
You need to use the window.prompt() method to prompt for user input in JS.
You need to create a button that the user can press to receive an alert. Add an event listener onto this button that prompts the user to enter a number. You can get help with this here. After you have the number from the prompt stored in a variable, use that variable to perform the different mathematical operations, and have these be added to the table.
You have extra line in your prompt code, please correct your code like below:
function isNotANumber(NaN) {
var isNotANumer = promptForAValidNumber("Please enter a valid number")
}
Also you must use standard method of prompt:
https://www.w3schools.com/jsref/met_win_prompt.asp
Infact you need to add the event listerner to listen for the click events.
May something like
<html lang="en">
<head>
<title>Assignment 2</title>
<style>
table, th, tr, td {
border-collapse: collapse;
}
table {
width: 80%;
margin: 10%;
}
th {
width: 33%;
border: 2px solid black;
justify-content: space-evenly;
height: 25px;
background-color: white;
}
td {
border: 1px solid black;
padding: 1%;
text-align: center;
background-color: greenyellow;
}
</style>
</head>
<body>
<table>
<tr>
<th>Number</th>
<th>Squared</th>
<th>Divided by Pi</th>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
<script>
function promptForNumber(promptString, min, max) {
Array.prototype.max = function() {
return Math.max.apply(null, this);
};
Array.prototype.min = function() {
return Math.min.apply(null, this);
};
}
function populateRow(row) {
var number = window.prompt("Enter your number");
var cell = row.getElementsByTagName("td");
cell[0].innerHTML = number;
cell[1].innerHTML = Math.pow(number, 2);
cell[2].innerHTML = (number / Math.PI).toFixed(4);
}
function isNotANumber(NaN) {
var isNotANumer = promptForAValidNumber("Please enter a valid number")
}
var table = document.getElementsByTagName("table")[0];
var rows = table.getElementsByTagName("tr");
console.log('rows', rows);
for (let i = 0; i < rows.length; i++) {
let currentRow = table.rows[i];
currentRow.addEventListener("click", function() {
populateRow(currentRow);
})
};
</script>
</body>
</html>
For me, the answer was putting the script tag of the JS file at the end of the HTML body tag.
<body>
<h1>Todo List</h1>
<ul>
<li>"new" - Add a Todo</li>
<li>"list" - List all Todos</li>
<li>"delete" - Remove specific Todo</li>
<li>"quit" - Quit App</li>
</ul>
<script src="app.js"></script>
</body>
</html>

Change background color onClick of column in a dynamically populated table

I am dynamically creating HTML table like this :
for(var i=0; i<rowsToAdd ; i++){
tr = table.insertRow(-1);
var colsToAddLength = findColsToAddLength();
for(var j=0; j<colsToAddLength; j++){
var tabCell = tr.insertCell(-1);
var colToAdd = findColToAdd();
tabCell.innerHTML = colToAdd;
}
}
How can I change the color of a particular cell once it's clicked? I am a beginner in web development.
You can use it like this:
function alternate(id){
if(document.getElementsByTagName){
var table = document.getElementById(id);
var rows = table.getElementsByTagName("tr");
for(i = 0; i < rows.length; i++){
//manipulate rows
if(i % 2 == 0){
rows[i].className = "even";
}else{
rows[i].className = "odd";
}
}
}
}
<style>
.odd{background-color: white;}
.even{background-color: gray;}
</style>
<table id="theTable">
<tr><td>0 - some txt</td></tr>
<tr><td>1 - some txt</td></tr>
<tr><td>2 - some txt</td></tr>
<tr><td>3 - some txt</td></tr>
<tr><td>4 - some txt</td></tr>
</table>
As I like to avoid JS whenever it's not too much trouble doing same thing with CSS, I would suggest below trick, however I can't fully reproduce your case as you provided too few details. Colors can be controlled via additional CSS classes.
table {
border-collapse: collapse;
}
td {
position: relative;
border: 1px solid #000000;
padding: 0;
}
.pseudo-checkbox {
position: absolute;
top: 0;
left: 0;
height: 100%;
width: 100%;
opacity: 0;
}
.cell-content {
padding: 10px;
}
.pseudo-checkbox:checked + .cell-content {
background: red;
}
<table>
<tbody>
<tr>
<td>
<input type="checkbox" class="pseudo-checkbox" />
<div class="cell-content">
123
</div>
</td>
<td>
<input type="checkbox" class="pseudo-checkbox" />
<div class="cell-content">
123
</div>
</td>
<td>
<input type="checkbox" class="pseudo-checkbox" />
<div class="cell-content">
123
</div>
</td>
</tr>
</tbody>
</table>

Next button only brings the first image and stops

I have been trying to create a next and back buttons that go through the images one by one that are in the table.
But the next button, it only brings the first image and stops.
How can the same button "next" have the function of going through all the images?
<p id = "slider"></p>
<div id="galDiv">
<style>
table, th, td {
border: 1px solid black;}
</style>
<table>
<tr>
<td id="1"><img src="gallery/a.jpg" style="width:100px;height:100px;"></td>
<td id="2"><img src="gallery/k.jpg" style="width:100px;height:100px;"></td>
<td id="3"><img src="gallery/2.jpg" style="width:100px;height:100px;" ></td>
<td id="4"><img src="gallery/3.jpg" style="width:100px;height:100px;" ></td>
</tr>
</table>
</div>
<button id="nxt">NEXT</button>
<script>
document.getElementById("nxt").onclick = function()
{myFunction()};
function myFunction() {
var div = document.getElementById('galDiv');
var nextSibling = div.nextSibling;
while(nextSibling && nextSibling.nodeType != 1) {
nextSibling = nextSibling.nextSibling }
}
</script>
How can also create a back button ?
If you are trying to create a facebook like image viewer, you shouldn't use table element.
In order to create such thing you should create a div with container fixed side ,within this div you should have a div with floating images and then your button should change the right position of the inner div.
Or you could use a jquery library such as http://www.jacklmoore.com/colorbox
Your code does nothing. The next sibling to #galDiv is the <button>.
Is this what you wanted?
document.getElementById("nxt").onclick = myFunction;
function myFunction() {
var picture = [
"firstPicture",
"secondPicture",
"thirdPicture",
"fourthPicture"
];
var place = {
"firstPicture": 0,
"secondPicture": 1,
"thirdPicture": 2,
"fourthPicture": 3
};
var table = document.querySelector('table');
if (!table.className) {
table.className = "firstPicture";
}
var nextPicture = (place[table.className] + 1) % 4;
table.className = picture[nextPicture];
}
img[src="gallery/a.jpg"] {
border: 5px solid red;
}
img[src="gallery/k.jpg"] {
border: 5px solid green;
}
img[src="gallery/2.jpg"] {
border: 5px solid blue;
}
img[src="gallery/3.jpg"] {
border: 5px solid black;
}
table {
border-collapse: collapse;
position: absolute;
padding: none;
border: none;
}
#galDiv {
width: 113px;
height: 113px;
overflow: hidden;
position: relative;
}
.firstPicture {
left: 0;
}
.secondPicture {
left: -112px;
}
.thirdPicture {
left: -224px;
}
.fourthPicture {
left: -336px;
}
<p id = "slider"></p>
<div id="galDiv">
<table>
<tr>
<td id="1"><img src="gallery/a.jpg" style="width:100px;height:100px;"></td>
<td id="2"><img src="gallery/k.jpg" style="width:100px;height:100px;"></td>
<td id="3"><img src="gallery/2.jpg" style="width:100px;height:100px;" ></td>
<td id="4"><img src="gallery/3.jpg" style="width:100px;height:100px;" ></td>
</tr>
</table>
</div>
<button id="nxt">NEXT</button>
I added the curimg attribute to the slider. Read the script for yourself. You'll need to add in modulus arithmetic to round around the table entries. As for the 'prev' function. Figure out the same thing with a -1 when selecting the tdnode.
Don't forget to set the curimg attribute after you append the child.
Good luck!
<p id = "slider" curimg='1'></p>
<div id="galDiv">
<style>
table, th, td {
border: 1px solid black;}
</style>
<table>
<tr>
<td id="1"><img src="gallery/a.jpg" style="width:100px;height:100px;"></td>
<td id="2"><img src="gallery/k.jpg" style="width:100px;height:100px;"></td>
<td id="3"><img src="gallery/2.jpg" style="width:100px;height:100px;" ></td>
<td id="4"><img src="gallery/3.jpg" style="width:100px;height:100px;" ></td>
</tr>
</table>
</div>
<button id="nxt">NEXT</button>
<script>
document.getElementById("nxt").onclick = function()
{myFunction()};
function myFunction() {
//Get the slider, parse the int of the 'curimg' attribute
cid = document.getElementById('slider');
current_image = parseInt( cid.getAttribute('curimg') );
//Get the td of that id+1
tdnode = document.getElementById(current_image + 1);
//Clone the image childNode into the slider.
cid.appendChild( td.childNodes[0].cloneNode() );
}
</script>

alternating table row backcolor without jQuery

Suppose this table :
<table>
<tr><td>AAAAAAAA</td><td>NNNNNNNNNN</td></tr>
<tr><td>AAAAAAAA</td><td>NNNNNNNNNN</td></tr>
<tr><td>AAAAAAAA</td><td>NNNNNNNNNN</td></tr>
<tr><td>AAAAAAAA</td><td>NNNNNNNNNN</td></tr>
<tr><td>AAAAAAAA</td><td>NNNNNNNNNN</td></tr>
</table>
With this CSS:
<style>
.even{background:red;}
</style>
How can I write a pure js code that adds even class to even tr's of table ? [No jQuery]
If you just need it for style reasons, you can use CSS3 selectors (no JavaScript needed):
tr:nth-child(odd) {
background-color: red;
}
tr:nth-child(even) {
background-color: green;
}
Give the table an ID:
<table id="mytable"></table>
then:
var i, len,
// assuming only one tbody
// if none specified, it is automatically generated (like in your example)
// if you were to have several you would have to iterate over those too
rows = document.getElementById("mytable").
getElementsByTagName("tbody")[0].
getElementsByTagName("tr");
for (i = 1, len = rows.length; i < len; i += 2) {
rows[i].className += " even";
}
Just grab the table element by ID and loop the rows adding classnames as in this fiddle
<table id='myTable'>
<tr><td>AAAAAAAA</td><td>NNNNNNNNNN</td></tr>
<tr><td>AAAAAAAA</td><td>NNNNNNNNNN</td></tr>
<tr><td>AAAAAAAA</td><td>NNNNNNNNNN</td></tr>
<tr><td>AAAAAAAA</td><td>NNNNNNNNNN</td></tr>
<tr><td>AAAAAAAA</td><td>NNNNNNNNNN</td></tr>
</table>
var table = document.getElementById('myTable');
var rows = table.getElementsByTagName("tr");
for(i = 0; i < rows.length; i++){
if(i % 2 == 0){
rows[i].className = "even";
}else{
rows[i].className = "odd";
}
}
How about this one from this page full of table style tips. It does both odd and even rows, but you can alter it to suit your situation.
<!-- Javascript goes in the document HEAD -->
<script type="text/javascript">
function altRows(id){
if(document.getElementsByTagName){
var table = document.getElementById(id);
var rows = table.getElementsByTagName("tr");
for(i = 0; i < rows.length; i++){
if(i % 2 == 0){
rows[i].className = "evenrowcolor";
}else{
rows[i].className = "oddrowcolor";
}
}
}
}
window.onload=function(){
altRows('alternatecolor');
}
</script>
<!-- CSS goes in the document HEAD or added to your external stylesheet -->
<style type="text/css">
table.altrowstable {
font-family: verdana,arial,sans-serif;
font-size:11px;
color:#333333;
border-width: 1px;
border-color: #a9c6c9;
border-collapse: collapse;
}
table.altrowstable th {
border-width: 1px;
padding: 8px;
border-style: solid;
border-color: #a9c6c9;
}
table.altrowstable td {
border-width: 1px;
padding: 8px;
border-style: solid;
border-color: #a9c6c9;
}
.oddrowcolor{
background-color:#d4e3e5;
}
.evenrowcolor{
background-color:#c3dde0;
}
</style>
<!-- Table goes in the document BODY -->
<table class="altrowstable" id="alternatecolor">
<tr>
<th>Info Header 1</th><th>Info Header 2</th><th>Info Header 3</th>
</tr>
<tr>
<td>Text 1A</td><td>Text 1B</td><td>Text 1C</td>
</tr>
<tr>
<td>Text 2A</td><td>Text 2B</td><td>Text 2C</td>
</tr>
</tr>
<tr>
<td>Text 3A</td><td>Text 3B</td><td>Text 3C</td>
</tr>
<tr>
<td>Text 4A</td><td>Text 4B</td><td>Text 4C</td>
</tr>
<tr>
<td>Text 5A</td><td>Text 5B</td><td>Text 5C</td>
</tr>
</table>
<!-- The table code can be found here: http://www.textfixer/resources/css-tables.php#css-table03 -->
I have corrected , here is answer:
<html>
<head>
<title></title>
<meta name="author" content="SAP"/>
<meta name="keywords" content="key1,key2"/>
<style>
.even{color:red;background:blue;}
</style>
<script type="text/javascript">
var i, len;
function onload() {
var i, len, rows = document.getElementById("mytable").getElementsByTagName("tr");
for (i = 1, len = rows.length; i < len; i += 2) {
rows[i].className += " even";
}
}
</script>
</head>
<body onload="onload()">
<table id="mytable">
<tr><td>AAAAAAAA</td><td>NNNNNNNNNN</td></tr>
<tr><td>AAAAAAAA</td><td>NNNNNNNNNN</td></tr>
<tr><td>AAAAAAAA</td><td>NNNNNNNNNN</td></tr>
<tr><td>AAAAAAAA</td><td>NNNNNNNNNN</td></tr>
<tr><td>AAAAAAAA</td><td>NNNNNNNNNN</td></tr>
</table>
</body>
</html>

Categories

Resources