loop through checkbox value to check if its checked - javascript

I am working on a thing there a user can input some data, date, activity, and time. And when the user clicks on add, it adds it to a table. This table contains a 4 cell (checkbox) that is checked. Now the point is that a user can add many rows with data and then click on the checkbox, if its unchecked it will not be send to JSON string, but the rows that are checked should be send!
The problem is if i have 1 row thats green and 1 row thats red its still print out all the rows when i click on send greenmarked data.
Below is the code:
<!doctype html>
<html lang="en">
<head>
<style>
table, td {
border: 1px solid black;
padding: 0 40px 0 40px;
}
tr {
background-color: #00FF00;
}
.Green {
background-color: #00FF00;
}
.Red {
background-color: #FF0000;
}
</style>
<meta charset="utf-8">
</head>
<body>
<form>
Date: <input type="text" id="Datum" name="Date">
Activ: <input type="text" id="Activity" name="Activ">
Time: <input type="text" id="time" name="Time">
</form>
<button onclick="AddRow()">Add Data!</button>
<table id="myTable">
<tr>
<td>Date</td>
<td>Activity</td>
<td>Time</td>
<td>Done?</td>
</tr>
</table>
<button id="buttonforsend" onclick="SendData()">Send greenmarked data! </button>
<script>
function AddRow()
{
var $check = document.createElement("INPUT");
$check.setAttribute("type", "checkbox");
$check.setAttribute("checked", "true");
$check.setAttribute("id", "checks");
$check.addEventListener("click", toggleClass);
function toggleClass() {
console.log("clicked");
if (this.checked == true)
{
this.parentNode.parentNode.className = "Green";
}
else
{
this.parentNode.parentNode.className = "Red";
}
}
var date = document.getElementById("Datum");
var activity = document.getElementById("Activity");
var time = document.getElementById("time");
var table = document.getElementById("myTable");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.insertCell(0).innerHTML= date.value;
row.insertCell(1).innerHTML= activity.value;
row.insertCell(2).innerHTML= time.value;
row.insertCell(3).appendChild($check).value;
}
function addTable() {
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('TABLE');
table.border='1';
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
for (var i=0; i<3; i++){
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (var j=0; j<4; j++){
var td = document.createElement('TD');
td.width='75';
td.appendChild(document.createTextNode("Cell " + i + "," + j));
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
function CheckData() {
var $arr = [];
var tb = document.getElementById("myTable");
var check = document.getElementById("checks");
for (var i = 0, row; row = tb.rows[i]; i++) {
for (var j = 0, col; col = row.cells[j]; j++) {
if(check.checked == true) {
$arr.push(col.firstChild.nodeValue);
}
}
}
return $arr;
}
function SendData()
{
var obj = {test: CheckData()};
var jsonString = "jsonString=" + (JSON.stringify(obj));
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST","JSON_H.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form- urlencoded");
xmlhttp.setRequestHeader("Content-Length", jsonString.length);
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState === 4 && (xmlhttp.status === 200)){
alert(xmlhttp.responseText);
}
};
xmlhttp.send(jsonString);
}
</script>
</body>
</html>

You can find all the checked checkboxes in the table, and then add only the values of rows with a checked checkbox
function AddRow() {
var $check = document.createElement("INPUT");
$check.setAttribute("type", "checkbox");
$check.setAttribute("checked", "true");
$check.setAttribute("class", "checks");
$check.addEventListener("click", toggleClass);
function toggleClass() {
if (this.checked == true) {
this.parentNode.parentNode.className = "Green";
} else {
this.parentNode.parentNode.className = "Red";
}
}
var date = document.getElementById("Datum");
var activity = document.getElementById("Activity");
var time = document.getElementById("time");
var table = document.getElementById("myTable");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.insertCell(0).innerHTML = date.value;
row.insertCell(1).innerHTML = activity.value;
row.insertCell(2).innerHTML = time.value;
row.insertCell(3).appendChild($check).value;
}
function addTable() {
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('TABLE');
table.border = '1';
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
for (var i = 0; i < 3; i++) {
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (var j = 0; j < 4; j++) {
var td = document.createElement('TD');
td.width = '75';
td.appendChild(document.createTextNode("Cell " + i + "," + j));
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
function CheckData() {
var $arr = [];
var tb = document.getElementById("myTable");
var checks = tb.querySelectorAll(".checks"),
chk, tr;
for (var i = 0; i < checks.length; i++) {
chk = checks[i];
if (chk.checked) {
tr = chk.closest ? chk.closest('tr') : chk.parentNode.parentNode;
$arr.push({
date: tr.cells[0].innerText,
activity: tr.cells[1].innerText
});
}
}
return $arr;
}
function SendData() {
var obj = {
test: CheckData()
};
var jsonString = "jsonString=" + (JSON.stringify(obj));
document.getElementById('jsonString').innerHTML = jsonString;
return; // for testing
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "JSON_H.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form- urlencoded");
xmlhttp.setRequestHeader("Content-Length", jsonString.length);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4 && (xmlhttp.status === 200)) {
alert(xmlhttp.responseText);
}
};
xmlhttp.send(jsonString);
}
table,
td {
border: 1px solid black;
padding: 0 40px 0 40px;
}
tr {
background-color: #00FF00;
}
.Green {
background-color: #00FF00;
}
.Red {
background-color: #FF0000;
}
<form>
Date:
<input type="text" id="Datum" name="Date">Activ:
<input type="text" id="Activity" name="Activ">Time:
<input type="text" id="time" name="Time">
</form>
<button onclick="AddRow()">Add Data!</button>
<table id="myTable">
<tr>
<td>Date</td>
<td>Activity</td>
<td>Time</td>
<td>Done?</td>
</tr>
</table>
<button id="buttonforsend" onclick="SendData()">Send greenmarked data!</button>
<pre id="jsonString"></pre>
Since, id of an element must be unique, the id attribute of checkbox is changed to class

Related

How to add the value of the table from the script tag to the table of the html where id = #show?

How to add the value of the table from the script tag to the table of the html where id = #show?
var arrHead = new Array();
arrHead = ['', 'Student Name', 'Department', 'Age'];
function createTable() {
var stuTable = document.createElement('table');
stuTable.setAttribute('id', 'stuTable');
var tr = stuTable.insertRow(-1);
for (var h = 0; h < arrHead.length; h++) {
var th = document.createElement('th');
th.innerHTML = arrHead[h];
tr.appendChild(th);
}
var div = document.getElementById('cont');
div.appendChild(stuTable);
}
function addRow() {
var stuTab = document.getElementById('stuTable');
var rowCnt = stuTab.rows.length;
var tr = stuTab.insertRow(rowCnt);
tr = stuTab.insertRow(rowCnt);
for (var c = 0; c < arrHead.length; c++) {
var td = document.createElement('td');
td = tr.insertCell(c);
if (c == 0) {
var button = document.createElement('input');
button.setAttribute('type', 'button');
button.setAttribute('value', 'Remove');
button.setAttribute('onclick', 'removeRow(this)');
td.appendChild(button);
}
else {
var ele = document.createElement('input');
ele.setAttribute('type', 'text');
ele.setAttribute('value', '');
td.appendChild(ele);
}
}
}
function removeRow(oButton) {
var stuTab = document.getElementById('stuTable');
stuTab.deleteRow(oButton.parentNode.parentNode.rowIndex);
}
function submit() {
var myTab = document.getElementById('stuTable');
var arrValues = new Array();
for (row = 1; row < myTab.rows.length - 1; row++) {
for (c = 0; c < myTab.rows[row].cells.length; c++) {
var element = myTab.rows.item(row).cells[c];
if (element.childNodes[0].getAttribute('type') == 'text') {
arrValues.push("'" + element.childNodes[0].value + "'");
}
}
}
var out = document.getElementById('#show');
document.write(arrValues);
}
table { width: 70%; }
table, th, td { border: solid 1px #DDD;
border-collapse: collapse; padding: 2px 3px; text-align: center;
}
<body onload="createTable()">
<p>
<input type="button" id="addRow" value="Add New Row" onclick="addRow()" />
</p>
<div id="cont"></div>
<p><input type="button" id="bt" value="Submit Data" onclick="submit()" /></p>
</body>
<footer>
<table border="4" id="show">
<thead>
<tr>
<th>name</th>
<th>dpt</th>
<th>age</th>
</tr>
</thead>
</table>
</thead>
</table>
</footer>
Just create a new row inside the table, loop through the array and create a cell for each item.
Here's the code snippet for the same:
var arrHead = new Array();
arrHead = ['', 'Student Name', 'Department', 'Age'];
function createTable() {
var stuTable = document.createElement('table');
stuTable.setAttribute('id', 'stuTable');
var tr = stuTable.insertRow(-1);
for (var h = 0; h < arrHead.length; h++) {
var th = document.createElement('th');
th.innerHTML = arrHead[h];
tr.appendChild(th);
}
var div = document.getElementById('cont');
div.appendChild(stuTable);
}
function addRow() {
var stuTab = document.getElementById('stuTable');
var rowCnt = stuTab.rows.length;
var tr = stuTab.insertRow(rowCnt);
tr = stuTab.insertRow(rowCnt);
for (var c = 0; c < arrHead.length; c++) {
var td = document.createElement('td');
td = tr.insertCell(c);
if (c == 0) {
var button = document.createElement('input');
button.setAttribute('type', 'button');
button.setAttribute('value', 'Remove');
button.setAttribute('onclick', 'removeRow(this)');
td.appendChild(button);
} else {
var ele = document.createElement('input');
ele.setAttribute('type', 'text');
ele.setAttribute('value', '');
td.appendChild(ele);
}
}
}
function removeRow(oButton) {
var stuTab = document.getElementById('stuTable');
stuTab.deleteRow(oButton.parentNode.parentNode.rowIndex);
}
function submit() {
var myTab = document.getElementById('stuTable');
var arrValues = new Array();
for (row = 1; row < myTab.rows.length - 1; row++) {
for (c = 0; c < myTab.rows[row].cells.length; c++) {
var element = myTab.rows.item(row).cells[c];
if (element.childNodes[0].getAttribute('type') == 'text') {
arrValues.push("'" + element.childNodes[0].value + "'");
}
}
}
var tbodyRef = document.querySelector('#show');
var newRow = tbodyRef.insertRow();
// Insert a cell at the end of the row
arrValues.forEach(item => {
var newCell = newRow.insertCell();
var newText = document.createTextNode(item);
newCell.appendChild(newText);
});
}
table {
width: 70%;
}
table,
th,
td {
border: solid 1px #DDD;
border-collapse: collapse;
padding: 2px 3px;
text-align: center;
}
<body onload="createTable()">
<p>
<input type="button" id="addRow" value="Add New Row" onclick="addRow()" />
</p>
<div id="cont"></div>
<p><input type="button" id="bt" value="Submit Data" onclick="submit()" /></p>
</body>
<footer>
<table border="4" id="show">
<thead>
<tr>
<th>name</th>
<th>dpt</th>
<th>age</th>
</tr>
</thead>
</table>
</thead>
</table>
</footer>

Import values from rows of one table to header of another table

I want to import values from a row of one table to the header of another table. The issue is that my code copies the selected row to a div where table 2 is present.
Also, the row has an input field in which I can enter a value. It copies the input field as a whole and not just the value. How can I import only the value of the input field?
var table;
$('#createPlist').click(function plrList() {
count = Number($('#noofTiks').val());
caption = $('<caption>');
table = $('<table>');
table = $(table).css({
"border": "1px solid black"
});
var thead = $('<thead>');
var htr = $('<tr>');
var tbody = $('<tbody>');
for (var a = 0; a < count; a++) {
var row = $('<tr>');
for (var b = 0; b < 2; b++) {
var td = $("<td>");
td = $(td).css({
"border": "1px solid black"
});
if (b == 0) {
var srNo = a + 1;
td.append(srNo);
} else {
var input = $('<input>');
td.append(input);
}
row.append(td);
}
tbody.append(row);
}
var th = $('<th>');
th.append("Sr. No.");
htr.append(th);
th = $('<th>');
th.append("Player Name");
htr.append(th);
thead.append(htr);
table.append(thead);
table.append(tbody);
caption.append("Player List");
$('#pList').append(caption);
$('#pList').append(table);
});
$('#createPlist').on('click', function() {
$(this).prop('disabled', true);
});
$('#giveTik').click(function() {
count = Number($('#noofTiks').val());
for (h = 0; h < count; h++) {
var table = $('<table>');
table = $(table).css({
"border": "1px solid black",
"margin": "20px auto",
"width": "500px",
"height": "250px"
})
var thead = $('<thead>');
var tbody = $('<tbody>');
for (var i = 0; i < 3; i++) {
// append new row to body
var row = $('<tr>');
//var row = '';
for (var j = 0; j < 9; j++) {
// append new td to row
var td = $("<td>");
td = $(td).css({
"border": "1px solid black",
})
td.append("");
row.append(td);
}
tbody.append(row);
}
var showTable = $('#pList').find('tr').eq(h + 1); //NEED HELP HERE
console.log(showTable)
// For "selected" row of table1 ..
var rowFromTable1 = showTable;
// .. Take a clone/copy of it ..
var clonedRowFromTable1 = rowFromTable1.clone(); //NEED HELP HERE
// .. And append the cloned row to the thead of table2
$('#div').append(clonedRowFromTable1);
// thead.append(h + 1);
// table.append(thead);
table.append(tbody);
$('#div').append(table);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="noofTiks">
<div id="pList"></div>
<button class="btn btn-error" id="createPlist">OK</button>
<div id="div"></div>
<button id="giveTik">CREATE TICKETS</button>
Your current code was appending row to div because you where directly appending the clone row to #div instead you should append the cloned row to thead and then append this thead to table.Also i have replace cloned row td with th and added colspan .
Demo Code :
var table;
$('#createPlist').click(function plrList() {
count = Number($('#noofTiks').val());
caption = $('<caption>');
table = $('<table>');
table = $(table).css({
"border": "1px solid black"
});
var thead = $('<thead>');
var htr = $('<tr>');
var tbody = $('<tbody>');
for (var a = 0; a < count; a++) {
var row = $('<tr>');
for (var b = 0; b < 2; b++) {
var td = $("<td>");
td = $(td).css({
"border": "1px solid black"
});
if (b == 0) {
var srNo = a + 1;
td.append(srNo);
} else {
var input = $('<input>');
td.append(input);
}
row.append(td);
}
tbody.append(row);
}
var th = $('<th>');
th.append("Sr. No.");
htr.append(th);
th = $('<th>');
th.append("Player Name");
htr.append(th);
thead.append(htr);
table.append(thead);
table.append(tbody);
caption.append("Player List");
$('#pList').append(caption);
$('#pList').append(table);
});
$('#createPlist').on('click', function() {
$(this).prop('disabled', true);
});
$('#giveTik').click(function() {
count = Number($('#noofTiks').val());
for (h = 0; h < count; h++) {
var table = $('<table>');
table = $(table).css({
"border": "1px solid black",
"margin": "20px auto",
"width": "500px",
"height": "250px"
})
var thead = $('<thead>');
var tbody = $('<tbody>');
for (var i = 0; i < 3; i++) {
// append new row to body
var row = $('<tr>');
//var row = '';
for (var j = 0; j < 9; j++) {
// append new td to row
var td = $("<td>");
td = $(td).css({
"border": "1px solid black",
})
td.append("");
row.append(td);
}
tbody.append(row);
}
var showTable = $('#pList').find('tr').eq(h + 1); //NEED HELP HERE
// For "selected" row of table1 ..
var rowFromTable1 = showTable;
// .. Take a clone/copy of it ..
var clonedRowFromTable1 = rowFromTable1.clone();
//finding input value
var input_value = clonedRowFromTable1.find("input").val();
//getting sr.no
var texts = clonedRowFromTable1.find("td:first").text();
//replace td with th and add sr.no and input value
clonedRowFromTable1.find("td:first").replaceWith("<th colspan='9'>" + texts + " " + input_value + "</th>")
clonedRowFromTable1.find("td:last").remove()//remove next td
//append cloned elemnt to thead
thead.append(clonedRowFromTable1);
table.append(thead)//append to table
table.append(tbody);
$('#div').append(table);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="noofTiks">
<div id="pList"></div>
<button class="btn btn-error" id="createPlist">OK</button>
<div id="div"></div>
<button id="giveTik">CREATE TICKETS</button>

Forbid row insertion | no jQuery

I have a dynamic table. Data comes from inputs by Create button click.
If at least one row includes current input ID-field value (not inserted yet) program should forbid row insertion.
I tried to add checkId() logic but it didn't work for me:
checkId = () => {
var isDuplicate = false;
var idVal = inputs[0].value;
if (textbox.value.includes(idVal)){
isDuplicate = true;
row.remove();
alert("Pease, enter unique ID")
}
return isDuplicate;
}
Is there any way to implement this logic within existing code (no jQuery)?
Here are both html and js:
let headerArr = new Array();
headerArr = ['ID', 'Fname', 'Lname', 'Age'];
//console.log(headerArr.length)
//inputs
var div = document.getElementById('enter');
var inputs = div.getElementsByTagName('input')
var count = 0;
createTable = () => {
let storage = document.createElement('table');
storage.setAttribute('id', 'storage'); //set the table ID
let row = storage.insertRow(-1);
for (let h = 0; h < headerArr.length; h++) { //table header
let headCols = document.createElement('th');
headCols.innerHTML = headerArr[h];
row.appendChild(headCols);
}
let div = document.getElementById('dynamicTable');
div.appendChild(storage); //add the table to the page
}
/* checkId = () => {
var isDuplicate = false;
var idVal = inputs[0].value;
//textbox = document.createElement('input')
if (textbox.value.includes(idVal)){
isDuplicate = true;
row.remove();
alert("Pease, enter unique ID")
}
return isDuplicate;
} */
//add a new row to the table
addEnd = () => {
let table = document.getElementById('storage');
var rowCount = table.rows.length; //get table row count
var row = table.insertRow(rowCount)
var textbox;
// if((!checkId()) && rowCount > 1){
for (let c = 0; c <= headerArr.length - 1; c++) {
var cell = document.createElement('td');
cell = row.insertCell(c);
textbox = document.createElement('input');
textbox.setAttribute('type', 'text');
textbox.setAttribute('readonly', true);
textbox.setAttribute('value', inputs[c].value);
cell.appendChild(textbox);
}
// }
}
let createBtn = document.getElementById('create-btn');
createBtn.addEventListener('click', addEnd, false);
<!DOCTYPE html>
<html>
<head>
<title>Table</title>
<style>
table {
width: 100px;
border-spacing: 10px;
padding: 10px;
}
table,
th,
td {
border: 1px solid gray;
border-collapse: collapse;
padding: 2px 3px;
text-align: left;
}
.enter {
display: block;
float: right;
margin-bottom: 10px
}
}
</style>
</head>
<body onload="createTable()">
<div id="dynamicTable"></div>
<div id="enter" class="enter">
<p>ID:<br>
<input class="enter__id" type="text" id="id"></input>
<br>
<p>First name:<br>
<input class="enter__name type=" text " id="name "></input>
<br>
<p>Last name:<br>
<input class="enter__surname type="text" id="surname"></input>
<br>
<p>Age:<br>
<input class="enter__age" type="text" id="age"></input>
<br>
<button id="create-btn">Create</button>
<button id="update-btn">Update</button>
</div>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
Please, help me to find the right way to solve it.
if (textbox.value.includes(idVal))
Your condition isn't valid, because you try to get .value from a variable that is undefined in your context.
I fix your js code :
let headerArr = new Array();
headerArr = ['ID', 'Fname', 'Lname', 'Age'];
//console.log(headerArr.length)
//inputs
var div = document.getElementById('enter');
var inputs = div.getElementsByTagName('input')
var count = 0;
createTable = () => {
let storage = document.createElement('table');
storage.setAttribute('id', 'storage'); //set the table ID
let row = storage.insertRow(-1);
for (let h = 0; h < headerArr.length; h++) { //table header
let headCols = document.createElement('th');
headCols.innerHTML = headerArr[h];
row.appendChild(headCols);
}
let div = document.getElementById('dynamicTable');
div.appendChild(storage); //add the table to the page
}
checkId = () => {
var idVal = inputs[0].value;
for (var i = 0; i < document.getElementsByClassName('id_cells').length; i++) {
let el_id = document.getElementsByClassName('id_cells');
if (el_id.value = idVal) {
alert("Pease, enter unique ID");
return true
}
}
return false;
}
//add a new row to the table
addEnd = () => {
let table = document.getElementById('storage');
var rowCount = table.rows.length; //get table row count
var row = table.insertRow(rowCount)
if ((!checkId()) && rowCount > 1) {
for (let c = 0; c <= headerArr.length - 1; c++) {
var cell = document.createElement('td');
cell = row.insertCell(c);
textbox = document.createElement('input');
textbox.setAttribute('type', 'text');
textbox.setAttribute('readonly', true);
textbox.setAttribute('value', inputs[c].value);
if (c == 0) {
textbox.setAttribute('class', 'id_cells');
}
cell.appendChild(textbox);
}
}
}
let createBtn = document.getElementById('create-btn');
createBtn.addEventListener('click', addEnd, false);
When you create your cells, if it's the first of the row (where the id should be displayed), I add a class to the cell to keep a reference. When you need to check for duplicate id, you get all the tag with the class i set beforehand and check their id in a loop.
I hope it solved your issue

Datatable not working properly

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();
}
});
}

Dynamic creation of table with DOM

Can someone tell me what's wrong with this code? I want to create a table with 2 columns and 3 rows, and in the cells I want Text1 and Text2 on every row. This code creates a table with 2 columns and 3 rows, but it's only text in the cells in the third row (the others are empty).
var tablearea = document.getElementById('tablearea');
var table = document.createElement('table');
var tr = [];
var td1 = document.createElement('td');
var td2 = document.createElement('td');
var text1 = document.createTextNode('Text1');
var text2 = document.createTextNode('Text2');
for (var i = 1; i < 4; i++){
tr[i] = document.createElement('tr');
for (var j = 1; j < 4; j++){
td1.appendChild(text1);
td2.appendChild(text2);
tr[i].appendChild(td1);
tr[i].appendChild(td2);
}
table.appendChild(tr[i]);
}
tablearea.appendChild(table);
You must create td and text nodes within loop. Your code creates only 2 td, so only 2 are visible. Example:
var table = document.createElement('table');
for (var i = 1; i < 4; i++){
var tr = document.createElement('tr');
var td1 = document.createElement('td');
var td2 = document.createElement('td');
var text1 = document.createTextNode('Text1');
var text2 = document.createTextNode('Text2');
td1.appendChild(text1);
td2.appendChild(text2);
tr.appendChild(td1);
tr.appendChild(td2);
table.appendChild(tr);
}
document.body.appendChild(table);
It is because you're only creating two td elements and 2 text nodes.
Creating all nodes in a loop
Recreate the nodes inside your loop:
var tablearea = document.getElementById('tablearea'),
table = document.createElement('table');
for (var i = 1; i < 4; i++) {
var tr = document.createElement('tr');
tr.appendChild( document.createElement('td') );
tr.appendChild( document.createElement('td') );
tr.cells[0].appendChild( document.createTextNode('Text1') )
tr.cells[1].appendChild( document.createTextNode('Text2') );
table.appendChild(tr);
}
tablearea.appendChild(table);
Creating then cloning in a loop
Create them beforehand, and clone them inside the loop:
var tablearea = document.getElementById('tablearea'),
table = document.createElement('table'),
tr = document.createElement('tr');
tr.appendChild( document.createElement('td') );
tr.appendChild( document.createElement('td') );
tr.cells[0].appendChild( document.createTextNode('Text1') )
tr.cells[1].appendChild( document.createTextNode('Text2') );
for (var i = 1; i < 4; i++) {
table.appendChild(tr.cloneNode( true ));
}
tablearea.appendChild(table);
Table factory with text string
Make a table factory:
function populateTable(table, rows, cells, content) {
if (!table) table = document.createElement('table');
for (var i = 0; i < rows; ++i) {
var row = document.createElement('tr');
for (var j = 0; j < cells; ++j) {
row.appendChild(document.createElement('td'));
row.cells[j].appendChild(document.createTextNode(content + (j + 1)));
}
table.appendChild(row);
}
return table;
}
And use it like this:
document.getElementById('tablearea')
.appendChild( populateTable(null, 3, 2, "Text") );
Table factory with text string or callback
The factory could easily be modified to accept a function as well for the fourth argument in order to populate the content of each cell in a more dynamic manner.
function populateTable(table, rows, cells, content) {
var is_func = (typeof content === 'function');
if (!table) table = document.createElement('table');
for (var i = 0; i < rows; ++i) {
var row = document.createElement('tr');
for (var j = 0; j < cells; ++j) {
row.appendChild(document.createElement('td'));
var text = !is_func ? (content + '') : content(table, i, j);
row.cells[j].appendChild(document.createTextNode(text));
}
table.appendChild(row);
}
return table;
}
Used like this:
document.getElementById('tablearea')
.appendChild(populateTable(null, 3, 2, function(t, r, c) {
return ' row: ' + r + ', cell: ' + c;
})
);
You need to create new TextNodes as well as td nodes for each column, not reuse them among all of the columns as your code is doing.
Edit:
Revise your code like so:
for (var i = 1; i < 4; i++)
{
tr[i] = document.createElement('tr');
var td1 = document.createElement('td');
var td2 = document.createElement('td');
td1.appendChild(document.createTextNode('Text1'));
td2.appendChild(document.createTextNode('Text2'));
tr[i].appendChild(td1);
tr[i].appendChild(td2);
table.appendChild(tr[i]);
}
<title>Registration Form</title>
<script>
var table;
function check() {
debugger;
var name = document.myForm.name.value;
if (name == "" || name == null) {
document.getElementById("span1").innerHTML = "Please enter the Name";
document.myform.name.focus();
document.getElementById("name").style.border = "2px solid red";
return false;
}
else {
document.getElementById("span1").innerHTML = "";
document.getElementById("name").style.border = "2px solid green";
}
var age = document.myForm.age.value;
var ageFormat = /^(([1][8-9])|([2-5][0-9])|(6[0]))$/gm;
if (age == "" || age == null) {
document.getElementById("span2").innerHTML = "Please provide Age";
document.myForm.age.focus();
document.getElementById("age").style.border = "2px solid red";
return false;
}
else if (!ageFormat.test(age)) {
document.getElementById("span2").innerHTML = "Age can't be leass than 18 and greater than 60";
document.myForm.age.focus();
document.getElementById("age").style.border = "2px solid red";
return false;
}
else {
document.getElementById("span2").innerHTML = "";
document.getElementById("age").style.border = "2px solid green";
}
var password = document.myForm.password.value;
if (document.myForm.password.length < 6) {
alert("Error: Password must contain at least six characters!");
document.myForm.password.focus();
document.getElementById("password").style.border = "2px solid red";
return false;
}
re = /[0-9]/g;
if (!re.test(password)) {
alert("Error: password must contain at least one number (0-9)!");
document.myForm.password.focus();
document.getElementById("password").style.border = "2px solid red";
return false;
}
re = /[a-z]/g;
if (!re.test(password)) {
alert("Error: password must contain at least one lowercase letter (a-z)!");
document.myForm.password.focus();
document.getElementById("password").style.border = "2px solid red";
return false;
}
re = /[A-Z]/g;
if (!re.test(password)) {
alert("Error: password must contain at least one uppercase letter (A-Z)!");
document.myForm.password.focus();
document.getElementById("password").style.border = "2px solid red";
return false;
}
re = /[$&+,:;=?##|'<>.^*()%!-]/g;
if (!re.test(password)) {
alert("Error: password must contain at least one special character!");
document.myForm.password.focus();
document.getElementById("password").style.border = "2px solid red";
return false;
}
else {
document.getElementById("span3").innerHTML = "";
document.getElementById("password").style.border = "2px solid green";
}
if (document.getElementById("data") == null)
createTable();
else {
appendRow();
}
return true;
}
function createTable() {
var myTableDiv = document.getElementById("myTable"); //indiv
table = document.createElement("TABLE"); //TABLE??
table.setAttribute("id", "data");
table.border = '1';
myTableDiv.appendChild(table); //appendChild() insert it in the document (table --> myTableDiv)
debugger;
var header = table.createTHead();
var th0 = table.tHead.appendChild(document.createElement("th"));
th0.innerHTML = "Name";
var th1 = table.tHead.appendChild(document.createElement("th"));
th1.innerHTML = "Age";
appendRow();
}
function appendRow() {
var name = document.myForm.name.value;
var age = document.myForm.age.value;
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.insertCell(0).innerHTML = name;
row.insertCell(1).innerHTML = age;
clearForm();
}
function clearForm() {
debugger;
document.myForm.name.value = "";
document.myForm.password.value = "";
document.myForm.age.value = "";
}
function restrictCharacters(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (((charCode >= '65') && (charCode <= '90')) || ((charCode >= '97') && (charCode <= '122')) || (charCode == '32')) {
return true;
}
else {
return false;
}
}
</script>
<div>
<form name="myForm">
<table id="tableid">
<tr>
<th>Name</th>
<td>
<input type="text" name="name" placeholder="Name" id="name" onkeypress="return restrictCharacters(event);" /></td>
<td><span id="span1"></span></td>
</tr>
<tr>
<th>Age</th>
<td>
<input type="text" onkeypress="return event.charCode === 0 || /\d/.test(String.fromCharCode(event.charCode));" placeholder="Age"
name="age" id="age" /></td>
<td><span id="span2"></span></td>
</tr>
<tr>
<th>Password</th>
<td>
<input type="password" name="password" id="password" placeholder="Password" /></td>
<td><span id="span3"></span></td>
</tr>
<tr>
<td></td>
<td>
<input type="button" value="Submit" onclick="check();" /></td>
<td>
<input type="reset" name="Reset" /></td>
</tr>
</table>
</form>
<div id="myTable">
</div>
</div>
var html = "";
for (var i = 0; i < data.length; i++){
html +="<tr>"+
"<td>"+ (i+1) + "</td>"+
"<td>"+ data[i].name + "</td>"+
"<td>"+ data[i].number + "</td>"+
"<td>"+ data[i].city + "</td>"+
"<td>"+ data[i].hobby + "</td>"+
"<td>"+ data[i].birthdate + "</td>"+"<td><button data-arrayIndex='"+ i +"' onclick='editData(this)'>Edit</button><button data-arrayIndex='"+ i +"' onclick='deleteData()'>Delete</button></td>"+"</tr>";
}
$("#tableHtml").html(html);
You can create a dynamic table rows as below:
var tbl = document.createElement('table');
tbl.style.width = '100%';
for (var i = 0; i < files.length; i++) {
tr = document.createElement('tr');
var td1 = document.createElement('td');
var td2 = document.createElement('td');
var td3 = document.createElement('td');
::::: // As many <td> you want
td1.appendChild(document.createTextNode());
td2.appendChild(document.createTextNode());
td3.appendChild(document.createTextNode();
tr.appendChild(td1);
tr.appendChild(td2);
tr.appendChild(td3);
tbl.appendChild(tr);
}
when you say 'appendchild' you actually move your child from one parent to another.
you have to create a node for each cell.
In my example, serial number is managed according to the actions taken on each row using css. I used a form inside each row, and when new row created then the form will get reset.
/*auto increment/decrement the sr.no.*/
body {
counter-reset: section;
}
i.srno {
counter-reset: subsection;
}
i.srno:before {
counter-increment: section;
content: counter(section);
}
/****/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type='text/javascript'>
$(document).ready(function () {
$('#POITable').on('change', 'select.search_type', function (e) {
var selectedval = $(this).val();
$(this).closest('td').next().html(selectedval);
});
});
</script>
<table id="POITable" border="1">
<tr>
<th>Sl No</th>
<th>Name</th>
<th>Your Name</th>
<th>Number</th>
<th>Input</th>
<th>Chars</th>
<th>Action</th>
</tr>
<tr>
<td><i class="srno"></i></td>
<td>
<select class="search_type" name="select_one">
<option value="">Select</option>
<option value="abc">abc</option>
<option value="def">def</option>
<option value="xyz">xyz</option>
</select>
</td>
<td></td>
<td>
<select name="select_two" >
<option value="">Select</option>
<option value="123">123</option>
<option value="456">456</option>
<option value="789">789</option>
</select>
</td>
<td><input type="text" size="8"/></td>
<td>
<select name="search_three[]" >
<option value="">Select</option>
<option value="one">1</option>
<option value="two">2</option>
<option value="three">3</option>
</select>
</td>
<td><button type="button" onclick="deleteRow(this)">-</button><button type="button" onclick="insRow()">+</button></td>
</tr>
</table>
<script type='text/javascript'>
function deleteRow(row)
{
var i = row.parentNode.parentNode.rowIndex;
document.getElementById('POITable').deleteRow(i);
}
function insRow()
{
var x = document.getElementById('POITable');
var new_row = x.rows[1].cloneNode(true);
var len = x.rows.length;
//new_row.cells[0].innerHTML = len; //auto increment the srno
var inp1 = new_row.cells[1].getElementsByTagName('select')[0];
inp1.id += len;
inp1.value = '';
new_row.cells[2].innerHTML = '';
new_row.cells[4].getElementsByTagName('input')[0].value = "";
x.appendChild(new_row);
}
</script>
Hope this helps.
In My example call add function from button click event and then get value from form control's and call function generateTable.
In generateTable Function check first Table is Generaed or not. If table is undefined then call generateHeader Funtion and Generate Header and then call addToRow function for adding new row in table.
<input type="button" class="custom-rounded-bttn bttn-save" value="Add" id="btnAdd" onclick="add()">
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="dataGridForItem">
</div>
</div>
</div>
//Call Function From Button click Event
var counts = 1;
function add(){
var Weightage = $('#Weightage').val();
var ItemName = $('#ItemName option:selected').text();
var ItemNamenum = $('#ItemName').val();
generateTable(Weightage,ItemName,ItemNamenum);
$('#Weightage').val('');
$('#ItemName').val(-1);
return true;
}
function generateTable(Weightage,ItemName,ItemNamenum){
var tableHtml = '';
if($("#rDataTable").html() == undefined){
tableHtml = generateHeader();
}else{
tableHtml = $("#rDataTable");
}
var temp = $("<div/>");
var row = addToRow(Weightage,ItemName,ItemNamenum);
$(temp).append($(row));
$("#dataGridForItem").html($(tableHtml).append($(temp).html()));
}
//Generate Header
function generateHeader(){
var html = "<table id='rDataTable' class='table table-striped'>";
html+="<tr class=''>";
html+="<td class='tb-heading ui-state-default'>"+'Sr.No'+"</td>";
html+="<td class='tb-heading ui-state-default'>"+'Item Name'+"</td>";
html+="<td class='tb-heading ui-state-default'>"+'Weightage'+"</td>";
html+="</tr></table>";
return html;
}
//Add New Row
function addToRow(Weightage,ItemName,ItemNamenum){
var html="<tr class='trObj'>";
html+="<td>"+counts+"</td>";
html+="<td>"+ItemName+"</td>";
html+="<td>"+Weightage+"</td>";
html+="</tr>";
counts++;
return html;
}
You can do that using LemonadeJS.
<html>
<script src="https://lemonadejs.net/v2/lemonade.js"></script>
<div id='root'></div>
<script>
var Component = (function() {
var self = {};
self.rows = [
{ title:'Google', description: 'The alpha search engine...' },
{ title:'Bind', description: 'The microsoft search engine...' },
{ title:'Duckduckgo', description: 'Privacy in the first place...' },
];
// Custom components such as List should always be unique inside a real tag.
var template = `<table cellpadding="6">
<thead><tr><th>Title</th><th>Description</th></th></thead>
<tbody #loop="self.rows">
<tr><td>{{self.title}}</td><td>{{self.description}}</td></tr>
</tbody>
</table>`;
return lemonade.element(template, self);
});
lemonade.render(Component, document.getElementById('root'));
</script>
</html>

Categories