element switch class but don't get styles of the new class - javascript

I'm working on a real-life timetable where you can watch where the students current be. They have six meetings a day. if a student exit the scool i want to delete him from the list. if i doubleclick the name i want to change the class from name to selected and change the backgoundcolor so if i would press the "Schüler löschen"-button all selected get deleted.
Here is the code:
function createTable(){
var table = document.getElementById('table');
for(var j = 0;j<names.length;j++) {
var row = document.createElement("tr");
row.classList.add('row');
for(i=0;i<8;i++){
if(i==0){
var cell = document.createElement("input");
cell.classList.add('name');
cell.value= names[j];
cell.addEventListener("dblclick", function(){
alert(cell.classList);
cell.classList.add('selected');
alert(cell.classList);
});
}else if(i==4){
var cell = document.createElement("td");
cell.classList.add('spacer');
}else{
var cell = document.createElement("td");
cell.classList.add('cell');
cell.textContent = '';
}
row.appendChild(cell);
}
table.children[0].appendChild(row);
}
}
createTable();
the css:
input.name {
width: 20em;
background-color: #00ff00;
}
input.selected{
background-color: #ff7f7f;
}
The problem is if i double click the field the color dosent switch to red it stays green but the alert()-function shows that the class has switched
i've also tried
cell.name {
width: 20em;
background-color: #00ff00;
}
cell.selected{
background-color: #ff7f7f;
}

You need to remove cell class, and use this in that scope.
Try this:
function createTable() {
var table = document.getElementById('table');
var names = ["TEST 1", " TEST 2"];
for (var j = 0; j < names.length; j++) {
var row = document.createElement("tr");
row.classList.add('row');
for (i = 0; i < 8; i++) {
if (i == 0) {
var cell = document.createElement("input");
cell.classList.add('name');
cell.value = names[j];
cell.addEventListener("dblclick", function () {
alert(cell.classList);
this.classList.remove('cell');
this.classList.add('selected');
alert(cell.classList);
});
} else if (i == 4) {
var cell = document.createElement("td");
cell.classList.add('spacer');
} else {
var cell = document.createElement("td");
cell.classList.remove('selected');
cell.classList.add('cell');
cell.textContent = '';
}
row.appendChild(cell);
}
table.children[0].appendChild(row);
}
}
createTable();
input.name {
width: 20em;
background-color: #00ff00;
}
input.selected{
background-color: #ff7f7f;
}
<table id="table"><tbody></tbody></table>
I didn't get why cell is input element and why do you need to added in tr

Related

How could I select an image in a table and then copy it to another td in a diffrent table

I'm making a program that generates 2 tables. First has 16 images that represent a menu or options that you can click and then by clicking it you select in. The second table is generated by inputting rows and cells. So the second table is by default blank and each cells is meant to by replaced by an image that you selected in the first table. I've managed to do everything but I don't completley understand how to do the selecting and setting the image. (I assume it has something to do with ids and then onclick()?)
stolpci = window.prompt("vpiši stevilo stolpcov:");
for (i2 = 0; i2 < 1;) {
if (stolpci < 11 || stolpci > 41) {
stolpci = window.prompt("Napačno število. Število mora biti večje od 10 in manjše od 40. Ponovno vpiši stevilo stolpcov:");
} else {
i2++;
}
}
vrstice = window.prompt("vpiši stevilo vrstic:");
for (i2 = 0; i2 < 1;) {
if (vrstice < 6 || vrstice > 11) {
vrstice = window.prompt("Napačno število. Število mora biti večje od 5 in manjše od 11. Ponovno vpiši stevilo vrstic:");
} else {
i2++;
}
}
function generateTable() {
const tbl = document.createElement("table");
const tblBody = document.createElement("tbody");
for (let i = 0; i < vrstice; i++) {
const row = document.createElement("tr");
row.id = i;
for (let j = 0; j < stolpci; j++) {
const cell = document.createElement("td");
const cellText = document.createTextNode(' ');
cell.appendChild(cellText);
row.appendChild(cell);
cell.id = j;
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
document.body.appendChild(tbl);
}
function options() {
const tbl = document.createElement("table");
const tblBody = document.createElement("tbody");
let nImage = 1;
for (let i = 0; i < 1; i++) {
const row = document.createElement("tr");
for (let j = 0; j < 16; j++) {
const cell = document.createElement("td");
const cellText = document.createTextNode("");
if (nImage > 16) {
nImage = 1;
}
cell.style.backgroundImage = "url('images/sprite" + nImage + ".gif')";
cell.id = nImage;
nImage++;
cell.appendChild(cellText);
row.appendChild(cell);
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
document.body.appendChild(tbl);
}
window.onload = () => {
options();
generateTable();
}
table {
border: 1px solid gray;
padding: 0px;
margin: 0px;
border-spacing: 0px;
}
td {
margin: 0px;
padding: 0px;
min-width: 32px;
max-width: 32px;
max-height: 32px;
min-height: 32px;
width: 32px;
height: 32px;
border: 1px solid gray;
background-color: silver;
}
You would need to add click events to each cell. When click you could have another object which you save the 'selected' data to i.e the cell data. You would then need a button which when clicked would move your 'selected' data to the cells in the other table.

Trying to find a way to make new columns with JS

I am building a table with JavaScript. If you check the link you can see it is all in one column, but I need the name. prices, and images in separate columns. I am honestly not sure where to start to do this, so I'm looking for some help.
https://jsfiddle.net/wL28gd10/
JS
window.addEventListener("load", function(){
// ARRAYs
var itemName = ["BLT", "PBJ", "TC", "HC", "GC"];
var itemPrice = ["$1", "$2", "$3", "$4", "$5"];
var itemPhoto =
["images/blt.jpg","images/pbj.jpg","images/tc.jpg","images/hc.jpg","images/gc.jpg"];
//Create HTML Table
var perrow = 1,
table = document.createElement("table"),
row = table.insertRow();
// Loop through itemName array
for (var i = 0; i < itemName.length; i++) {
// Add cell
var cell = row.insertCell();
cell.innerHTML = itemName[i];
// Brreak into next row
var next = i + 1;
if (next%perrow==0 && next!=itemName.length) {
row = table.insertRow();
}
}
// Loop through itemPrice array
for (var i = 0; i < itemPrice.length; i++) {
// Add cell
var cell = row.insertCell();
cell.innerHTML = itemPrice[i];
// Break into next row
var next = i + 1;
if (next%perrow==0 && next!=itemPrice.length) {
row = table.insertRow();
}
}
// Loop through itemPhoto array
for (var i = 0; i < itemPhoto.length; i++) {
// Add cell
var cell = row.insertCell();
cell.innerHTML = itemPhoto[i];
// Break into next row
var next = i + 1;
if (next%perrow==0 && next!=itemPhoto.length) {
row = table.insertRow();
}
}
// Attach table to HTML id "menu-table"
document.getElementById("menu-table").appendChild(table);
});
Just create all of your columns in one loop, like:
for (var i = 0; i < itemName.length; i++) {
var row = table.insertRow();
// Add cell
var cell = row.insertCell();
cell.innerHTML = itemName[i];
cell = row.insertCell();
cell.innerHTML = itemPrice[i];
// Add cell
cell = row.insertCell();
cell.innerHTML = itemPhoto[i];
}
You only really need one loop.
window.addEventListener("load", function(){
// ARRAYs
var itemName = ["BLT", "PBJ", "TC", "HC", "GC"];
var itemPrice = ["$1", "$2", "$3", "$4", "$5"];
var itemPhoto = ["images/blt.jpg","images/pbj.jpg","images/tc.jpg","images/hc.jpg","images/gc.jpg"];
//Create HTML Table
var perrow = 1,
table = document.createElement("table");
// Loop through itemName array
for (var i = 0; i < itemName.length; i++) {
let row = table.insertRow();
// Add cell
var cell = row.insertCell();
cell.innerHTML = itemName[i];
var cell = row.insertCell();
cell.innerHTML = itemPrice[i];
var cell = row.insertCell();
cell.innerHTML = itemPhoto[i];
}
// Attach table to HTML id "menu-table"
document.getElementById("menu-table").appendChild(table);
});
table { border-collapse: collapse; }
table tr td {
border: 1px solid black;
padding: 10px;
background-color: white;
}
<div id="menu-table"></div>

Set input to read only?

I am trying to build a grade book web app. I wanted to be able to edit the table cells to input grades, but I can't set it to readonly. What am I doing wrong?
I tried changing the code in the save button, but nothing works. I cant seem to get the input tags for some reason.Am I missing something? Is there another way to try to set the cells to readOnly? I tried getting the td tags, but that didn't work.
var myTable = document.getElementById("myTable");
var r = 0;
var c = 1;
function addRow() {
//insert a row
var row = myTable.insertRow(r);
//insert cells into a row
var cell = row.insertCell(0);
cell.innerHTML = "Students[i]";
r++;
}
function addColumn() {
//add new cell to each row
var allRows = document.getElementsByTagName("tr");
for (var i = 0; i < allRows.length; i++) {
row2 = allRows[i];
cell2 = allRows[i].insertCell(c);
cell2.innerHTML = "Puff";
}
}
function editCell() {
var allCells = document.getElementsByTagName("td");
for (var j = 0; j < allCells.length; j++) {
//clear text, then put in input box
allCells[j].innerHTML = "";
var myInput = document.createElement("input");
myInput.type = "text";
myInput.readOnly = false;
allCells[j].appendChild(myInput);
}
}
function saveData() {
//turn all inputs into readOnly
var allInputs = document.getElementsByTagName("td");
for (var k = 0; k < allInputs.length; k++) {
allInputs[k].id = "inpoot";
document.getElementById("inpoot").readOnly = true;
}
//document.getElementsByTagName("input").readOnly = true;
}
table,
th,
td {
border: 1px solid black;
border-collapse: collapse;
}
<table id="myTable"></table>
<button onClick="addRow()">Students</button>
<button onClick="addColumn()">Days</button>
<button onClick="editCell()">Edit</button>
<button onClick="savaData()">Save</button>
HTML IDs must be globally unique within a document. Since you're setting the ID to inpoot for each one, then the getElementById call is always going to be selecting the same element. Also, these elements are the tds, not the inputs themselves.
Try changing your save function thusly:
function saveData(){
//turn all inputs into readOnly
document.querySelectorAll("td > input").forEach(input => {
input.readOnly = true;
});
}
Is there another way to try to set the cells to readOnly?
Use this :
JS :
var myInput = document.createElement("input");
myInput.classList.add("readOnly-input");
CSS :
.readOnly-input{ pointer-events: none; }
The user can't interact when pointer-events are set to none. Let me know if you need more explaination.

selecting multiple table row using shift key and control key is not working

hi i have a editable table which is created by using java script.here i use some code for selection process .i want select table row using control key and shift key . i get the code from
[1]: http://jsfiddle.net/g8Rpe/ here. this example shown for html table .but my table is daynamic one
the code is here:
/******for table**************/
$(function () {
function tableCreate() {
var body = document.body,
tbl = document.createElement('table');
tbl.style.width = '100%';
tbl.style.borderCollapse = 'collapse';
for (var i = 0; i < 30; i++) {
var tr = tbl.insertRow();
tr.setAttribute("data-id", i, 0);
for (var j = 0; j < 3; j++) {
var td = tr.insertCell();
td.appendChild(document.createTextNode(''));
}
}
$("body").append(tbl);
$("td").addClass("mainheading4")
$("tr").on("onmousedown=RowClick(this,false)")
}
tableCreate();
//******************for editable table*************************//
$('td').click(function () {
$('td').attr('contenteditable', 'true');
})
//************for multiple selection*****************//
var lastSelectedRow;
var trs = document.getElementById('table').tBodies[0].getElementsByTagName('tr');
// disable text selection
document.onselectstart = function () {
return false;
}
function RowClick(currenttr, lock) {
if (window.event.ctrlKey) {
toggleRow(currenttr);
}
if (window.event.button === 0) {
if (!window.event.ctrlKey && !window.event.shiftKey) {
clearAll();
toggleRow(currenttr);
}
if (window.event.shiftKey) {
selectRowsBetweenIndexes([lastSelectedRow.rowIndex, currenttr.rowIndex])
}
}
}
function toggleRow(row) {
row.className = row.className == 'selected' ? '' : 'selected';
lastSelectedRow = row;
}
function selectRowsBetweenIndexes(indexes) {
indexes.sort(function (a, b) {
return a - b;
});
for (var i = indexes[0]; i <= indexes[1]; i++) {
trs[i - 1].className = 'selected';
}
}
function clearAll() {
for (var i = 0; i < trs.length; i++) {
trs[i].className = '';
}
}
});
body{font-size:62.5%;}
td { padding: 0.2em 0.4em; }
.selected { background: lightBlue }
.mainheading4{
border: 1px solid;
border-color: lightgray;
width:33.3%;
height:17px;
font-size:15px;
padding-left: -5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
i use
$("tr").on("mousedown=RowClick(this,false)") <
for getting mouse event.
but its not taken.
There are couple of wrong doings.
1) Assign id to table without which you will not get table rows as in below line
var trs = document.getElementById('table').tBodies[0].getElementsByTagName('tr');
E.g. In your tableCreate method add below lines of code.
var body = document.body,
tbl = document.createElement('table'),
tableId = document.createAttribute('id');
tableId.value = "table";
tbl.setAttributeNode(tableId);
2) Second register mouse down event like suggested by feela,
$(document).on('click', 'tr', function () {
RowClick(this, false);
});
Hope it will resolve your issue.
This is not a valid syntax for on. See: http://api.jquery.com/on/
What you probably meant was:
$("tr").on("mousedown", function(event) {
RowClick(event.target, false);
});

How to check value of table td?

I am trying to create mine field game. "I am very new to Js".
What I have done so far:
var level = prompt("Choose Level: easy, medium, hard");
if (level === "easy") {
level = 3;
} else if (level === "medium") {
level = 6;
} else if (level === "hard") {
level = 9;
}
var body = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
for (var i = 1; i <= 10; i++) {
var row = document.createElement("tr");
document.write("<br/>");
for (var x = 1; x <= 10; x++) {
var j = Math.floor(Math.random() * 12 + 1);
if (j < level) {
j = "mined";
} else {
j = "clear";
}
var cell = document.createElement("td");
var cellText = document.createTextNode(j + " ");
cell.appendChild(cellText);
row.appendChild(cell);
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
body.appendChild(tbl);
tbl.setAttribute("border", "2");
So I create here 2d table and enter 2 random values in rows and columns (mined or clear).
Where I am stuck is:
Check if td = mined it dies otherwise open the box(td) etc.
How do I assign value of td? I mean how can I check which value(mined/clear) there is in the td which is clicked?
Ps: Please don't write the whole code:) just show me the track please:)
Thnx for the answers!
Ok! I came this far.. But if I click on row it gives sometimes clear even if I click on mined row or vice versa!
// create the table
var body = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
tbl.setAttribute('id','myTable');
var tblBody = document.createElement("tbody");
//Create 2d table with mined/clear
for(var i=1;i<=10;i++)
{
var row = document.createElement("tr");
document.write("<br/>" );
for(var x=1;x<=10;x++)
{
var j=Math.floor(Math.random()*12+1);
if(j<level)
{
j = "mined";
}
else{
j = "clear";
}
var cell = document.createElement("td");
var cellText = document.createTextNode(j + "");
cell.appendChild(cellText);
row.appendChild(cell);
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
body.appendChild(tbl);
tbl.setAttribute("border", "2");
//Check which row is clicked
window.onload = addRowHandlers;
function addRowHandlers() {
var table = document.getElementById("myTable");
var rows = table.getElementsByTagName("tr");
for (i = 0; i < rows.length; i++) {
var currentRow = table.rows[i];
var createClickHandler =
function(row)
{
return function() {
var cell = row.getElementsByTagName("td")[0];
var id = cell.innerHTML;
if(id === "mined")
{
alert("You died");
}else
{
alert("clear");
}
};
}
currentRow.onclick = createClickHandler(currentRow);
}
}
I think I do something wrong with giving the table id "myTable"..
Can you see it?
Thank you in advance!
So, the idea would be:
assign a click event to each td cell:
td.addEventListener('click', mycallback, false);
in the event handler (callback), check the content of the td:
function mycallback(e) { /*e.target is the td; check td.innerText;*/ }
Pedagogic resources:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/td?redirectlocale=en-US&redirectslug=HTML%2FElement%2Ftd
https://developer.mozilla.org/en-US/docs/DOM/EventTarget.addEventListener
JavaScript, getting value of a td with id name

Categories