I have a calendar table, that shows the entire month's date, if user chose to see next month or previous I need to delete the entire table and replace the new table in that same place, at the moment each table is loading underneath the other because I cant get this to work.
I need to remove table from calendar-dates. but I had no luck. I have used removechild("tb") but didnt work, I also tried var test = document.getElementById("calendarDates");
test.removeChild(test.childNodes[0]);
Here is the code for the table:
document.getElementById("calendar-dates").appendChild(calendar);
Table:
//add calendar table
function get_calendar(day_no, days, m , y){
var table = document.createElement('table');
table.id = "tb";
var tr = document.createElement('tr');
//row for the day letters
for(var c=0; c<=6; c++){
var td = document.createElement('td');
td.innerHTML = "SMTWTFS"[c];
tr.appendChild(td);
}
table.appendChild(tr);
//create 2nd row
tr = document.createElement('tr');
var c;
for(c=0; c<=6; c++){
if(c == day_no){
break;
}
var td = document.createElement('td');
td.innerHTML = "";
tr.appendChild(td);
}
var count = 1;
for(; c<=6; c++){
var td = document.createElement('td');
td.innerHTML = count;
td.style.cursor = "pointer";
td.id = count;
td.onclick = function () {
m = m + 1;
document.getElementById("cDD").value = this.id + "/" + m + "/" + y;
document.getElementById("calendar-container").style.display = "none";
};
count++;
tr.appendChild(td);
}
table.appendChild(tr);
//rest of the date rows
for(var r=3; r<=7; r++){
tr = document.createElement('tr');
for(var c=0; c<=6; c++){
if(count > days){
table.appendChild(tr);
return table;
}
var td = document.createElement('td');
td.innerHTML = count;
td.style.cursor = "pointer";
td.id = count;
td.onclick = function () {
m = m + 1;
document.getElementById("cDD").value = this.id + "/" + m + "/" + y;
document.getElementById("calendar-container").style.display = "none";
};
count++;
tr.appendChild(td);
}
table.appendChild(tr);
}
return table;
}
The removeChild method takes a node, not an ID.
test.removeChild(test.childNodes[0]); probably doesn't work because you have some text nodes before the table.
test.removeChild(test.firstElementChild)probably will work
document.getElementById("calendar-dates").removeChild(document.getElementById('tb'))
document.querySelector('button').addEventListener('click', () => {
document.getElementById('wrapper').removeChild(document.querySelector('table'));
})
table, th, td {
border: 1px solid red;
padding: 2px
}
<div id="wrapper">
<table>
<tr>
<td>Table</td>
<td>Content</td>
</tr>
</table>
</div>
<button>Remove table</button>
Does #calendar-dates contains other html than tables? If not, you can set innerHtml to empty
var calendarDates = document.getElementById("calendar-dates");
calendarDates.innerHtml = '';
calendarDates.appendChild(calendar);
Related
I am building a dynamic table where i want only 3 values from my json to display and make one a link which when clicked on, the rest displays. Below is my code kindly assist please.
var myInvestment =[
{
"investmentNo":"00032",
"amount":"70000",
"status": "Expired",
"repayAmt":"70500",
"description": "Official",
"maturityDate":"2020-10-31"
},
{
"investmentNo":"00034",
"amount":"5000",
"status": "Current",
"repayAmt":"6000",
"description": "School fees",
"maturityDate":"2022-03-31"
}
]
var investmentTable = document.querySelector("#investmentTable");
if(myInvestment.length>0){
var col = []; // define an empty array
for (var i = 0; i < myInvestment.length; i++) {
for (var key in myInvestment[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}
// CREATE TABLE HEAD .
var tHead = document.createElement("tHead");
// CREATE ROW FOR TABLE HEAD .
var hRow = document.createElement("tr");
// ADD COLUMN HEADER TO ROW OF TABLE HEAD.
tHead.appendChild(hRow);
investmentTable.appendChild(tHead);
// CREATE TABLE BODY .
var tBody = document.createElement("tbody");
// ADD COLUMN HEADER TO ROW OF TABLE HEAD.
for (var i = 0; i < myInvestment.length; i++) {
var bRow = document.createElement("tr");
// CREATE ROW FOR EACH RECORD .
var td = document.createElement("td");
td.innerHTML = i+1;
bRow.appendChild(td);
for (var j = 0; j < 3; j++) {
var td = document.createElement("td");
if (j==0) {
td.innerHTML = ''+myInvestment[i][col[j]]+ '';
bRow.appendChild(td);
}else{
td.innerHTML = myInvestment[i][col[j]];
bRow.appendChild(td);
}if (j==2) {
td.innerHTML = '<div class="badge">'+myInvestment[i][col[j]]+ '</div>';
if (td.textContent=="Current") {
td.innerHTML = '<div class="badge badge-success">'+myInvestment[i][col[j]]+ '</div>';
} else {
td.innerHTML = '<div class="badge badge-danger">'+myInvestment[i][col[j]]+ '</div>';
}
}
tBody.appendChild(bRow)
}
investmentTable.appendChild(tBody);
}
}
This is my modal function that will display the second table
function invModalView(k,myInvestment){
var modal = document.getElementById("modal-block-normal");
modal.style.display = "block";
var investNo = document.getElementById("investNo");
var investmentTableModal = document.querySelector("#investmentTableModal");
myInvestment
.forEach((item, i) => {
var row = investmentTable.insertRow();
row.insertCell(0).innerHTML = item.repayAmt;
row.insertCell(1).innerHTML = item.description;
row.insertCell(2).innerHTML = item.maturityDate;
});
}
}
HTML
<table class="table table-bordered table-striped table-vcenter table-responsive" id="investmentTableModal">
<thead id="invtableHead">
<tr >
<th class="d-sm-table-cell" style="width: 30%;">Repayment Amount</th>
<td id="repayAmt"></td>
</tr>
<tr>
<th class="d-sm-table-cell" style="width: 30%;">Description</th>
<td id="description"></td>
</tr>
<tr>
<th class="d-sm-table-cell" style="width: 30%;">Maturity Date</th>
<td id = "matureDate"></td>
</tr>
</table>
i want when a user clicks on myInvestment.investmentNo[0], only the repaymentamt, description and maturityDate of myInvestment[0] will show
That's a lot of spaghetti code to go through, so I'm not even going to try.
In jQuery, what people normally do is they iterate over the array and construct each button, and then place each button on the dom. Then, they apply a $.click() on that button, and inside the .click callback they can create a clojure over the original item they created a button for.
like this: https://jsfiddle.net/0d8aL9xr/
var items = [{title: 'a bouncing ball', id: 1}, {title: 'a rubber duck', id: 2}];
items.forEach(item => {
const $newButton = $(`<button>${item.title}</button>`);
$('.buttons').append($newButton);
$newButton.click(function() {
$('#item-id').val(item.id);
$('#item-name').val(item.title);
})
})
function setSession(key,value){
window.localStorage.setItem(key, value);
}
function getSession(key){
return window.localStorage.getItem(key)
;
}
function unsetSession(key){
window.localStorage.removeItem(key)
;
}
////// Investment page scripts //////
function investmentData(){
var InvData = getSession("InvData");
var myInvestment = JSON.parse(InvData);
var investmentTable = document.querySelector("#investmentTable");
if(myInvestment.investments.length>0){
var col = []; // define an empty array
for (var i = 0; i < myInvestment.investments.length; i++) {
for (var key in myInvestment.investments[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}
// CREATE TABLE HEAD .
var tHead = document.querySelector("#tableHead");
// CREATE ROW FOR TABLE HEAD .
var hRow = document.querySelector("#tableRow");
// ADD COLUMN HEADER TO ROW OF TABLE HEAD.
tHead.appendChild(hRow);
investmentTable.appendChild(tHead);
// CREATE TABLE BODY .
var tBody = document.createElement("tbody");
// ADD COLUMN HEADER TO ROW OF TABLE HEAD.
for (var i = 0; i < myInvestment.investments.length; i++) {
var bRow = document.createElement("tr");
// CREATE ROW FOR EACH RECORD .
var td = document.createElement("td");
td.innerHTML = i+1;
bRow.appendChild(td);
for (var j = 0; j < 3; j++) {
var td = document.createElement("td");
if (j==0) {
td.innerHTML = ''+myInvestment.investments[i][col[j]]+ '';
bRow.appendChild(td);
}else{
td.innerHTML = myInvestment.investments[i][col[j]];
bRow.appendChild(td);
}if (j==2) {
td.innerHTML = '<div class="badge">'+myInvestment.investments[i][col[j]]+ '</div>';
if (td.textContent=="Current") {
td.innerHTML = '<div class="badge badge-success">'+myInvestment.investments[i][col[j]]+ '</div>';
} else {
td.innerHTML = '<div class="badge badge-danger">'+myInvestment.investments[i][col[j]]+ '</div>';
}
}
tBody.appendChild(bRow)
}
investmentTable.appendChild(tBody);
}
}
}
function invModalView(k){
$('#investmentTableModal').empty();
var myInv = JSON.parse(getSession("InvData"));
var modal = document.getElementById("modal-block-normal");
modal.style.display = "block";
var investmentTableModal = document.querySelector("#investmentTableModal");
// CREATE TABLE BODY .
var tBody = document.createElement("tbody");
// // ADD COLUMN HEADER TO ROW OF TABLE HEAD.
// // Investment No
var bRow = document.createElement("tr");
var th = document.createElement("th");
th.innerHTML = "Investment No";
var td2 = document.createElement("td");
td2.style.width = "30%";
th.style.width = "30%";
td2.innerHTML = myInv.investments[k].investmentNo;
bRow.appendChild(th);
bRow.appendChild(td2);
tBody.appendChild(bRow);
investmentTableModal.appendChild(tBody)
// Investment duration
var tBody = document.createElement("tbody");
var bRow = document.createElement("tr");
var th = document.createElement("th");
th.innerHTML = "Duration";
var td2 = document.createElement("td");
td2.innerHTML = myInv.investments[k].duration;
bRow.appendChild(th);
bRow.appendChild(td2);
tBody.appendChild(bRow)
investmentTableModal.appendChild(tBody);
// investment start date
var tBody = document.createElement("tbody");
var bRow = document.createElement("tr");
var th = document.createElement("th");
th.innerHTML = "startDate";
var td2 = document.createElement("td");
td2.innerHTML = myInv.investments[k].startDate;
bRow.appendChild(th);
bRow.appendChild(td2);
tBody.appendChild(bRow)
investmentTableModal.appendChild(tBody);
// investment yield
var tBody = document.createElement("tbody");
var bRow = document.createElement("tr");
var th = document.createElement("th");
th.innerHTML = "Yield";
var td2 = document.createElement("td");
td2.innerHTML = myInv.investments[k].yield;
bRow.appendChild(th);
bRow.appendChild(td2);
tBody.appendChild(bRow)
investmentTableModal.appendChild(tBody);
// investment repayment Amount
var tBody = document.createElement("tbody");
var bRow = document.createElement("tr");
var th = document.createElement("th");
th.innerHTML = "Repayment Amount";
var td2 = document.createElement("td");
td2.innerHTML = myInv.investments[k].repayAmt;
bRow.appendChild(th);
bRow.appendChild(td2);
tBody.appendChild(bRow)
investmentTableModal.appendChild(tBody);
// investment description
var tBody = document.createElement("tbody");
var bRow = document.createElement("tr");
var th = document.createElement("th");
th.innerHTML = "Description";
var td2 = document.createElement("td");
td2.innerHTML = myInv.investments[k].description;
bRow.appendChild(th);
bRow.appendChild(td2);
tBody.appendChild(bRow)
investmentTableModal.appendChild(tBody);
// investment maturityDate
var tBody = document.createElement("tbody");
var bRow = document.createElement("tr");
var th = document.createElement("th");
th.innerHTML = "MaturityDate";
var td2 = document.createElement("td");
td2.innerHTML = myInv.investments[k].maturityDate;
bRow.appendChild(th);
bRow.appendChild(td2);
tBody.appendChild(bRow)
investmentTableModal.appendChild(tBody);
}
////// Create Localstorage for MyInvestment ////
var myInvestment = '{"investments":[{"investmentNo":"00032","amount":"70000","status": "Expired","duration": "2","startDate": "2020-02-02","yield": "2.60","repayAmt":"70500","description": "Official","maturityDate":"2020-10-31"},{"investmentNo":"00033","amount":"40000","status": "Current","duration": "3","startDate": "2019-01-05","yield": "12.0","repayAmt":"42000","description": "Personal","maturityDate":"2020-12-31"},{"investmentNo":"00034","amount":"5000","status": "Current","duration": "4","startDate": "5-04-2008","yield": "20.0","repayAmt":"6000","description": "School fees","maturityDate":"2022-03-31"}]}'
setSession("InvData",myInvestment);
I later succeeded in getting this. i think it would be nice to share for someone out there who might need it.
I am trying to create a table with title to be displayed on the first and second row and first column. The first row will have the same name which is working fine. But with my below script the row title (starting from 3rd row) displays in the last column than the first.
Please advise where am I going wrong with this.
var body = document.getElementsByTagName("body")[0];
var yardName = "B1";
var colsInYard = 5;
var rowsInYard = 5;
var tbl = document.createElement("table");
tbl.setAttribute("id", "our_table");
var tblHead = document.createElement("thead");
for (var r = 0; r < 1; r++) {
// creates a table row
var row = document.createElement("tr");
for (var c = 0; c <= colsInYard; c++) {
var cell = document.createElement("td");
if (c != 0) {
var cellText = document.createTextNode(yardName);
cell.appendChild(cellText);
row.appendChild(cell);
} else {
var cellText = document.createTextNode(" ");
cell.appendChild(cellText);
row.appendChild(cell);
}
}
tblHead.appendChild(row);
}
for (var r = 0; r < 1; r++) {
var row = document.createElement("tr");
for (var c = 0; c <= colsInYard; c++) {
var cell = document.createElement("td");
if (c != 0) {
var cellText = document.createTextNode(c);
cell.appendChild(cellText);
row.appendChild(cell);
} else {
var cellText = document.createTextNode(" ");
cell.appendChild(cellText);
row.appendChild(cell);
}
}
tblHead.appendChild(row);
}
tbl.appendChild(tblHead);
var tblBody = document.createElement("tbody");
for (var r = 1; r <= rowsInYard; r++) {
var row = document.createElement("tr");
var cellText = document.createTextNode(r);
for (var c = 0; c <= colsInYard; c++) {
var cell = document.createElement("td");
cell.appendChild(cellText);
row.appendChild(cell);
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
body.appendChild(tbl);
tbl.setAttribute("border", "0");
tbl.setAttribute("cellpadding", "0");
tbl.setAttribute("cellspacing", "0");
My fiddle https://jsfiddle.net/udopgxLv/1/
I believe you just need to add an IF statement to the code in the tbody section to get the data to post into the first column. I modified your jfiddle with the code below (just 2 lines added) and the values are inserted properly.
for (var r = 1; r <= rowsInYard; r++) {
var row = document.createElement("tr");
var cellText = document.createTextNode(r);
for (var c = 0; c <= colsInYard; c++) {
var cell = document.createElement("td");
if (c==1){ // <--- this was added
cell.appendChild(cellText);
} // <--- this was also added
row.appendChild(cell);
}
tblBody.appendChild(row);
}
You missed if statement in create tbody
for (var c = 0; c <= colsInYard; c++) {
var cell = document.createElement("td");
if (c=== 0)
cell.appendChild(cellText);
row.appendChild(cell);
}
https://jsfiddle.net/udopgxLv/3/
I'm writing simple table generator using JavaScript. I wrote function createChild() just like this:
function createTable(row_count, column_count) {
var table = document.createElement("table");
for (row = 0; row < row_count; row++) {
let tr = document.createElement("tr");
for (column = 0; column < column_count; column++) {
let td = document.createElement("td");
td.innerHTML = "a<sub>(" + (row+1) + "," + (column+1) + ")</sub>";
tr.appendChild(td);
}
table.appendChild(tr);
}
table.setAttribute("border", "1");
var tableHolder = document.getElementById("table-container");
var oldTable = tableHolder.firstChild;
if (!oldTable) {
tableHolder.appendChild(table);
}
else {
tableHolder.firstChild.replaceWith(table);
//tableHolder.replaceChild(tableHolder.firstChild, table);
}
}
The problem occurs at these lines:
tableHolder.firstChild.replaceWith(table);
//tableHolder.replaceChild(tableHolder.firstChild, table);
If I use first line, It works alright but when I switch it to second line, It doesn't work with error Uncaught DOMException: Failed to execute 'replaceChild' on 'Node': The node to be replaced is not a child of this node.
I can't figure out what's wrong.. please help.
You accidentally switched the order of the arguments passed to Node#replaceChild. The node to be inserted comes before the node to be replaced, somewhat counter-intuitively:
tableHolder.replaceChild(table, tableHolder.firstChild);
Demo Snippet:
function createTable(row_count, column_count) {
var table = document.createElement("table");
for (row = 0; row < row_count; row++) {
let tr = document.createElement("tr");
for (column = 0; column < column_count; column++) {
let td = document.createElement("td");
td.innerHTML = "a<sub>(" + (row+1) + "," + (column+1) + ")</sub>";
tr.appendChild(td);
}
table.appendChild(tr);
}
table.setAttribute("border", "1");
var tableHolder = document.getElementById("table-container");
var oldTable = tableHolder.firstChild;
if (!oldTable) {
tableHolder.appendChild(table);
}
else {
//tableHolder.firstChild.replaceWith(table);
tableHolder.replaceChild(table, tableHolder.firstChild);
}
}
createTable(10, 10)
<div id="table-container"></div>
please check updated fiddler.there is an update in replace Child.
http://jsfiddle.net/HB7LU/28302/
enter code here`
tableHolder.replaceChild(table, tableHolder.firstChild);
So I am generating a table with results which are returned from a JSON that is searched through and I would like to table to have pagionation, search, sorting options so I decided to use Data Tables. The table is being generated and populated with the correct results but the sorting options, the search and the pagination options do not appear at all. What am I doing wrong?
<!DOCTYPE html>
<html lang="en">
<head>
<title>Конкуренција</title>
</head>
<body>
<div id="cars" class="cars-container"></div>
<label for="amount">Цена:</label>
<input type="text" class="price-range-slider" id="amount" onclick="myFunction()" readonly style="border:0; color:#f6932f; font-weight:bold">
<div id="slider-range" style="width:300px"></div>
<br>
<p>
<label for="sili">Коњски сили:</label>
<input type="text" id="sili" onclick="myFunction()" readonly style="border:0; color:#f6931f; font-weight:bold;">
<div id="rejndz" style="width:300px" ></div>
<div>
<h4><label>Бренд</label></h4>
<select id="brand" multiple="multiple" onclick="myFunction()" data- style="btn-primary">
</select>
</div>
<br>
<div>
<h4><label>Тип на мотор</label></h4>
<select id="engineCap" multiple="multiple" onclick="myFunction()" >
</select>
<button onclick="myFunction(); dataTable(); ">Барај</button>
</table>
var selected = [];
var kapacitet = [];
var cena = [];
var hp = [];
var niza = [];
var finalKola = [];
function addTable() {
document.getElementById("results").innerHTML = "";
var myTableDiv = document.getElementById("results")
var tableBody = document.createElement('TBODY')
myTableDiv.border = '1'
myTableDiv.appendChild(tableBody);
var heading = [];
heading[0] = "Бренд"
heading[1] = "Модел"
heading[2] = "Капацитет"
heading[3] = "Коњски сили"
heading[4] = "Цена"
//koloni
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (a = 0; a < heading.length; a++) {
var th = document.createElement('TH')
th.width = '75';
th.appendChild(document.createTextNode(heading[a]));
tr.appendChild(th);
}
//table rows
for (a = 0; a < finalKola.length; a++) {
var tr = document.createElement('TR');
var td = document.createElement('TD')
td.appendChild(document.createTextNode(finalKola[a].Brand));
tr.appendChild(td);
var td = document.createElement('TD')
td.appendChild(document.createTextNode(finalKola[a].Model));
tr.appendChild(td);
var td = document.createElement('TD')
td.appendChild(document.createTextNode(finalKola[a].engineCap));
tr.appendChild(td);
var td = document.createElement('TD')
td.appendChild(document.createTextNode(finalKola[a].sili));
tr.appendChild(td);
var td = document.createElement('TD')
td.appendChild(document.createTextNode(finalKola[a].amount + " €"));
tr.appendChild(td);
tableBody.appendChild(tr);
}
$(document).ready(function (){
{
$('#results').dataTable();
}
});
}
These are the errors I get in console:
Uncaught TypeError: Cannot read property 'mData' of undefined
at HTMLTableCellElement.<anonymous> (jquery.dataTables.min.js:88)
at Function.each (jquery.js:368)
at HTMLTableElement.<anonymous> (jquery.dataTables.min.js:88)
at Function.each (jquery.js:368)
at jQuery.fn.init.each (jquery.js:157)
at jQuery.fn.init.p [as dataTable] (jquery.dataTables.min.js:80)
at dataTable (index.html:268)
at HTMLButtonElement.onclick (index.html:75)
Assigning value to finalKola in the following code. This code takes values from two range slider and two buttons and searches through a JSON.
for(var u=0;u<koli.length;u++)
{
if((koli[u].sili > minSili) && (koli[u].sili < maxSili) && (parseInt(koli[u].amount.replace(',','')) > minCena) && (parseInt(koli[u].amount.replace(',','')) < maxCena))
{
if( (kapacitet.length > 0 && $.inArray(koli[u].engineCap,kapacitet) != -1) &&
(selected.length > 0 && $.inArray(koli[u].Brand,selected) != -1))
{
finalKola.push(koli[u]);
}
else if(kapacitet.length == 0 && selected.length == 0)
{
finalKola.push(koli[u]);
}
else if((kapacitet.length > 0 && $.inArray(koli[u].engineCap,kapacitet) != -1) &&
(selected.length == 0))
{
finalKola.push(koli[u]);
}
else if((selected.length > 0 && $.inArray(koli[u].Brand,selected) != -1) &&
(kapacitet.length == 0))
{
finalKola.push(koli[u]);
}
}
}
I think DataTable is not applying on your table as you are applying datatable on $(document).ready and creating table in your function.
You can apply datatable after you have created the table.
function addTable() {
document.getElementById("results").innerHTML = "";
var myTableDiv = document.getElementById("results")
var tableBody = document.createElement('TBODY')
myTableDiv.border = '1'
myTableDiv.appendChild(tableBody);
var heading = [];
heading[0] = "Бренд"
heading[1] = "Модел"
heading[2] = "Капацитет"
heading[3] = "Коњски сили"
heading[4] = "Цена"
//koloni
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (a = 0; a < heading.length; a++) {
var th = document.createElement('TH')
th.width = '75';
th.appendChild(document.createTextNode(heading[a]));
tr.appendChild(th);
}
//table rows
for (a = 0; a < finalKola.length; a++) {
var tr = document.createElement('TR');
var td = document.createElement('TD')
td.appendChild(document.createTextNode(finalKola[a].Brand));
tr.appendChild(td);
var td = document.createElement('TD')
td.appendChild(document.createTextNode(finalKola[a].Model));
tr.appendChild(td);
var td = document.createElement('TD')
td.appendChild(document.createTextNode(finalKola[a].engineCap));
tr.appendChild(td);
var td = document.createElement('TD')
td.appendChild(document.createTextNode(finalKola[a].sili));
tr.appendChild(td);
var td = document.createElement('TD')
td.appendChild(document.createTextNode(finalKola[a].amount + " €"));
tr.appendChild(td);
tableBody.appendChild(tr);
}
$('#results').dataTable().fnDestroy();
$('#results').dataTable();
}
Your script is adding tbody before the thead, changed that to append Thead tr first and then tbody.
var selected = [];
var kapacitet = [];
var cena = [];
var hp = [];
var niza = [];
var finalKola = [];
function addTable() {
document.getElementById("results").innerHTML = "";
var myTableDiv = document.getElementById("results")
var tableBody = document.createElement('TBODY')
myTableDiv.border = '1'
var heading = [];
heading[0] = "Бренд"
heading[1] = "Модел"
heading[2] = "Капацитет"
heading[3] = "Коњски сили"
heading[4] = "Цена"
//koloni
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (a = 0; a < heading.length; a++) {
var th = document.createElement('TH')
th.width = '75';
th.appendChild(document.createTextNode(heading[a]));
tr.appendChild(th);
}
myTableDiv.appendChild(tableBody);
//table rows
for (a = 0; a < finalKola.length; a++) {
var tr = document.createElement('TR');
var td = document.createElement('TD')
td.appendChild(document.createTextNode(finalKola[a].Brand));
tr.appendChild(td);
var td = document.createElement('TD')
td.appendChild(document.createTextNode(finalKola[a].Model));
tr.appendChild(td);
var td = document.createElement('TD')
td.appendChild(document.createTextNode(finalKola[a].engineCap));
tr.appendChild(td);
var td = document.createElement('TD')
td.appendChild(document.createTextNode(finalKola[a].sili));
tr.appendChild(td);
var td = document.createElement('TD')
td.appendChild(document.createTextNode(finalKola[a].amount + " €"));
tr.appendChild(td);
tableBody.appendChild(tr);
}
$(document).ready(function (){
{
$('#results').dataTable();
}
});
}
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