Append table array value to another array - javascript

I have this code below that popups the cell value whenever the user clicks a specific cell.
What I'm currently trying to do is when the user clicks a cell i want that cell value to be appended to another column. I tried using the push method but it doesn't seem to be working. I'm not sure if I'm doing it the wrong way
JFiddle
HTML:
<table id="fruitsTable" class="fruitstableroni skillsTable class">
<thead></thead>
<tbody></tbody>
</table>
JavaScript:
var tbl = document.getElementById("fruitsTable");
if (tbl != null) {
for (var i = 0; i < tbl.rows.length; i++) {
for (var j = 0; j < tbl.rows[i].cells.length; j++)
tbl.rows[i].cells[j].onclick = function () {
obj[key2].push(this); //Trying to push it to the second column.
console.log(this);
};
}
}
function getval(cel) {
//console.log(cel.innerHTML);
}
var obj = {};
var key = "Red Fruits";
obj[key] = ['Apple', 'Cherry', 'Strawberry'];
var myArray = [];
myArray.push(obj);
var key2 = "Green Fruits";
obj[key2] = ['Watermelon', 'Durian', 'Avacado'];
var myArray2 = [];
myArray2.push(obj);
var key3 = "Random Fruits";
obj[key3] = ['Soursop', 'Papaya', 'Pineapple', 'Melon'];
var myArray3 = [];
myArray3.push(obj);
var $header = $("<tr>"),
cols = 0,
bodyString = "";
$.each(obj, function(key, values) {
cols = Math.max(cols, values.length); // find the longest
$header.append($('<th/>').text(key + ": " + values.length));
});
for (var i = 0; i < cols; i++) { // or use .map, but this is more undertandable for beginners
bodyString += '<tr>';
$.each(obj, function(key, values) {
bodyString += '<td>' +
(values[i] ? values[i] : "") + // ternary - instead of using if/else
'</td>';
});
bodyString += '</tr>';
}
$('.fruitsTableClass thead').html($header);
$('.fruitsTableClass tbody').html(bodyString);
var tbl = document.getElementById("fruitsTable");
if (tbl != null) {
for (var i = 0; i < tbl.rows.length; i++) {
for (var j = 0; j < tbl.rows[i].cells.length; j++)
tbl.rows[i].cells[j].onclick = function() {
getval(this);
obj[key2].push(this);
};
}
}
function getval(cel) {
alert(cel.innerHTML);
}
.class {
font-family: Open Sans;
}
.center {
display: flex;
justify-content: center
}
.skillsTable th {
border-left: 1px solid #AAA5A4;
border-right: 1px solid #AAA5A4;
}
table {
float: left;
border-collapse: collapse;
width: 70%
}
td {
border-left: 1px solid #AAA5A4;
border-right: 1px solid #AAA5A4;
padding-top: 8px;
padding-left: 11px;
font-size: 15px;
}
th {
color: #0080ff;
font-weight: normal;
border-bottom: 1px solid #AAA5A4;
padding-bottom: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="center">
<table id="fruitsTable" class="fruitsTableClass skillsTable class">
<thead></thead>
<tbody></tbody>
</table>
</div>

Restructure your code to have a method to redraw UI and to enable event listeners:
function redraw (obj) {
var $header = $('<tr>'),
cols = 0,
bodyString = ''
$.each(obj, function (key, values) {
cols = Math.max(cols, values.length) // find the longest
$header.append($('<th/>').text(key + ': ' + values.length))
})
for (var i = 0; i < cols; i++) { // or use .map, but this is more undertandable for beginners
bodyString += '<tr>'
$.each(obj, function (key, values) {
bodyString += '<td>' +
(values[i] ? values[i] : '') + // ternary - instead of using if/else
'</td>'
})
bodyString += '</tr>'
}
$('.fruitsTableClass thead').html($header)
$('.fruitsTableClass tbody').html(bodyString)
}
function listener (obj) {
tbl = document.getElementById('fruitsTable')
if (tbl != null) {
for (var i = 0; i < tbl.rows.length; i++) {
for (var j = 0; j < tbl.rows[i].cells.length; j++)
tbl.rows[i].cells[j].onclick = function () {
getval(this)
obj[key2].push(this.innerHTML)
redraw(obj)
listener(obj)
};
}
}
}
function getval (cel) {
alert(cel.innerHTML)
}
redraw(obj)
listener(obj)
JSFiddle - https://jsfiddle.net/gnm8wv5f/

To add rows or cells to a table, you should use the methods insertRow() and insertCell().
Example, if you want to add a cell at the beginning of a row (from w3schools):
var row = document.getElementById("myRow");
var x = row.insertCell(0);
x.innerHTML = "New cell";
Or, to insert at the end:
var x = row.insertCell(row.cells.length);
Using cells.length you can find the number of cells in a particluar row, in that way you could know where to insert the new cell.
More info in: w3 | MDN

Try this code.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
var daraArray=[];
$(document).ready(function(){
$(".classTd").click(function(){
//console.log($(this).html());
daraArray.push($(this).html());
console.log(daraArray);
});
});
</script>
<style type="text/css">
.classTd{
text-align: center;
}
</style>
</head>
<table id="fruitsTable" class="fruitstableroni skillsTable class" border="1">
<thead></thead>
<tbody>
<tr>
<td class="classTd" width="10%">1</td>
<td class="classTd" width="10%">2</td>
<td class="classTd" width="10%">3</td>
</tr>
<tr>
<td class="classTd" width="10%">4</td>
<td class="classTd" width="10%">5</td>
<td class="classTd" width="10%">6</td>
</tr>
<tr>
<td class="classTd" width="10%">7</td>
<td class="classTd" width="10%">8</td>
<td class="classTd" width="10%">9</td>
</tr>
</tbody>
</table>
</html>

The other answers here are good but you should definitely try AngularJs. The ng-repeat tag will easily cater your functionality.

Related

How can I create a multi-option dynamic dropdown in a table?

I am trying to make a dynamic multi-select option dropdown. The text for the options element in the dropdown are coming from a database that I am fetching. I want each row in the table to have the last column contain this multi-select option dropdown. Right now, the result is it's skipping every row and only on the last row is it displaying all the options multiple times (as amount of times as there are rows). So instead of showing in each row, every row is empty expect the last one and the values are all being showed in the final row. Also, strangely it created empty white space on the right side of the table, like it make new columns. I have attached an image to help visualize this.
How do I display the options properly in each row and how do I make it a multi select dropdown, where if the user clicks one of the options, that option is added to the impact area section.
Thanks.
Image: Image of how it currently looks
Javascript:
//Get Resources and corresponding information and display it in a table
function getResources(){
fetch("______", {
}).then(data => {
var table = document.getElementById("productivity-table");
for(var i=0; i < data.length; i++){
var row = table.insertRow(table.rows.length - 1);
var cell3 = row.insertCell(2);
cell3.classList.add("table-data");
//Cell3 - Create ul and li
var impact_ul = document.createElement("ul");
var impact_li = document.createElement("li");
impact_li.innerHTML = data[i].entity;
impact_li.setAttribute("style", "list-style-type:none");
//Add delete button row
var delete_span = document.createElement("span");
delete_span.className = "delete";
delete_span.innerHTML = "×"
impact_li.appendChild(delete_span);
impact_ul.appendChild(impact_li);
cell3.appendChild(impact_ul);
//Cell5 - Create department dropdown
var dep_dropdown = document.createElement('select');
console.log("dep dropdown", dep_dropdown);
//dep_dropdown.length = 0;
let dep_default = document.createElement('option');
dep_default.text = 'Select Department';
dep_default.disabled = true;
dep_dropdown.add(dep_default);
dep_dropdown.selectedIndex = 0;
fetch("______", {
}).then(data =>{
for(var i=0; i < data.length; i++){
var cell5 = row.insertCell(4);
cell5.classList.add("table-data");
var dep_option = document.createElement('option');
dep_option.text = data[i].dept_name;
dep_option.value = data[i]._id;
dep_dropdown.appendChild(dep_option);
cell5.appendChild(dep_dropdown);
}
}).catch(function(err) {
console.log('Fetch problem: ' + err);
});
}
})
}
here is what you asked for take alook on the snippet
window.onload = function() {
var data = ["option1", "option2", "option3", "option4"];
var table = document.getElementById("productivity-table");
function addslct(dep_dropdown) {
dep_dropdown = document.createElement('select');
dep_dropdown.size = "3";
dep_dropdown.className = "dep_select";
dep_dropdown.id = 'selection';
dep_dropdown.name = 'data options';
dep_dropdown.multiple = "multiple";
dep_dropdown.style.position = "relative";
dep_dropdown.style.width = "100%";
dep_dropdown.style.textAlign = "center";
dep_dropdown.style.color = "darkblue";
return dep_dropdown;
}
function addopts(data) {
var slcts = document.getElementsByClassName('dep_select');
for (var i = 0; i < slcts.length; i++) {
for (var a = 0; a < data.length; a++) {
slcts[i].options.add(optns(data[a], data[a]));
}
}
}
function optns(option, oname) {
var option = document.createElement('option');
option.Value = option;
option.textContent = oname;
return option;
}
table.rows[0].innerHTML += "<th>4</th>";
for (var i = 1; i < table.rows.length; i++) {
var newell = table.rows[i].cells.length;
table.rows[i].insertCell(newell);
table.rows[i].cells[table.rows.length - 1].appendChild(addslct());
}
addopts(data);
document.querySelectorAll('.dep_select').forEach(selectedOptions => {
selectedOptions.addEventListener('click', function() {
var col2 = this.options;
for (var o = 0; o < col2.length; o++) {
var o2 = col2[o];
if (o2.selected == true) {
var rwi = this.parentNode.parentNode.rowIndex;
var cli = this.parentNode.cellIndex;
var cell2 = table.rows[rwi].cells[cli-2];
var slctdopt = o2.value;
if (cell2.innerText.includes(slctdopt) == true) {
var excludez = cell2.innerText.replace("[ "+ slctdopt +" ]", "");
cell2.innerText = excludez + " [ " + slctdopt +" ]";
//cell2.innerText += " [ " + slctdopt +" ]";
} else {
excludez = slctdopt;
cell2.innerText += " [ "+ excludez +" ]";
}
}
}
});
});
}
#productivity-table {
font-family: Arial, Helvetica, sans-serif;
border-collapse: collapse;
width: 100%;
}
#productivity-table td,
#productivity-table th {
border: 1px solid #ddd;
padding: 8px;
}
#productivity-table td {
text-align: center;
color: blue;
margin: auto;
width:20%;
}
#productivity-table tr:nth-child(even) {
background-color: #f2f2f2;
}
#productivity-table tr:hover {
background-color: #ddd;
}
#productivity-table th {
padding-top: 12px;
padding-bottom: 12px;
text-align: center;
background-color: #4CAF50;
color: white;
}
<table class="table1" id="productivity-table">
<tr>
<th>1</th>
<th>2</th>
<th>3</th>
</tr>
<tr>
<td>first</td>
<td></td>
<td>third</td>
</tr>
<tr>
<td>first</td>
<td>[ option2 ]</td>
<td>third</td>
</tr>
<tr>
<td>first</td>
<td>[ option3 ]</td>
<td>third</td>
</tr>
</table>

Is it possible to create a table automatically?

Im beginner. I use a HTML table code like this (see below) for Unicode print using char's Decimal values:
<table border="1">
<tr><td>1</td><td></td>
<tr><td>2</td><td></td>
<tr><td>3</td><td></td>
...
<!-- last one: thousandth row -->
<tr><td>1000</td><td>Ϩ</td>
</table>
Is it possible to convert this code into an auto-generated table as follows using JavaScript or JQuery?
<table border="1">
<tr><td>rowNumber</td><td>innerHTML = "\u0026\u0023 + rowNumber + \u003B";</td>
...
<!-- thousandth row -->
<tr><td>rowNumber</td><td>innerHTML = "\u0026\u0023 + rowNumber + \u003B";</td>
</table>
You can start by creating a record-generating function.
function generateRecords(recordFn, limit) {
var records = [];
for (var i = 0; i < limit; i++) {
records.push(recordFn.call(null, i, records));
}
return records;
}
Then you can generate the JSON.
generateRecords(i => {
return {
dec: i,
entity: '&&num;' + i + '&semi;',
rendered: '&#' + i + ';'
}
}, 1000);
Finally, all you need to do is render the JSON to a table.
Example
(function($) {
$.fn.attrs = function(attrs) {
var $self = this;
if (attrs != null) {
$.each(attrs, function(attr, value) {
$self.attr(attr, value);
});
return $self;
} else {
var result = {};
$.each(this[0].attributes, function(index, attribute) {
result[attribute.name] = attribute.value;
});
return result;
}
};
$.fn.tableFromJson = function(data, attrs, indexField) {
return this.replaceWith($.tableFromJson.apply(this, arguments));
};
$.tableFromJson = function(data, attrs, indexField) {
var fields = Object.keys(data[0]);
if (indexField != null) fields.unshift(indexField);
return $('<table>')
.append($('<thead>').append($('<tr>').append(fields
.map(field => $('<th>').text(field)))))
.append($('<tbody>').append(data
.map((rec, row) => $('<tr>').append(fields
.map((field, col) => $('<td>').html(field === indexField ? (row + 1) : rec[field])))))).attrs(attrs);
};
})(jQuery);
function generateRecords(recordFn, limit) {
var records = [];
for (var i = 0; i < limit; i++) {
records.push(recordFn.call(null, i, records));
}
return records;
}
$('.column:nth-child(1) .result').tableFromJson(generateRecords(i => {
return {
dec: i,
entity: '&&num;' + i + '&semi;',
rendered: '&#' + i + ';'
}
}, 1000), $('.column:nth-child(1) .result').attrs());
$('.column:nth-child(2) .result').tableFromJson(generateRecords(i => {
return {
dec: i,
rendered: '\u0026\u0023' + i + '\u003B'
}
}, 1000), $('.column:nth-child(2) .result').attrs());
.container { width: 100%; }
.column { display: inline-block; width: 49%; }
table.result {
margin-bottom: 0.5em;
}
table.result,
table.result th,
table.result td {
border: 1px solid black;
border-collapse: collapse;
}
table.result th,
table.result td {
padding: 0.25em;
}
table.result tbody tr td {
text-align: center;
}
table.result thead tr {
background: #BBB;
}
table.result tbody tr:nth-child(even) {
background: #EEE;
}
table.result tbody tr:nth-child(odd) {
background: #FFF;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="column">
<table class="result"></table>
</div>
<div class="column">
<table class="result"></table>
</div>
</div>
You can try with this
var table = $('<table>').prop('border', 1);
for(i=0; i<1000; i++){
var row = $('<tr><td>' + i + '</td><td>&#'++'</td></tr>'
table.append(row);
}
$('#mytable').append(table);
Yes, Thats possible using javascript/JQuery.For that you need to use proper js code. Below is the sample code that can help you to create table and row,data using jquery.
Below code is responsible to create table tag
$('.class-name').append('<table border="3"></table>');
This will create table element inside your HTML having classname as .class-name.
Once the table tag is created you can create table row and data element as below.
$("table").append(createRow());
function createRow(){
var firstVal = '1st val';
var secondVal = '2nd val';
var tr = '<tr>' ;
tr += '<td>' + firstVal + '</td>';
tr += '<td>' + secondVal + '</td>';
tr +='</tr>';
return tr;
}
This code will generate the table row and will print the table data as st val and 2nd val.
Hope this code may help you

Moving table row to another table

I have this code below that prints the value of random fruits table whenever i click the cell value. The problem is i'm trying to create a function that allows me to move the value of random fruits table into the red fruits table by clicking on for example kiwi and it will move into the red fruits table and also i want to be able to move back that value i moved into red fruits table back to the random fruits table. I tried to do it using the array push method but it only copies the value into the other table and not completely move it. Is there any easy way to do this any suggestion would be greatly appreciated thanks!
var obj = {};
var obj2 = {};
var key = "Red Fruits";
obj[key] = ['Apple', 'Cherry', 'Strawberry'];
var myArray = [];
myArray.push(obj);
var key2 = "Green Fruits";
obj[key2] = ['Watermelon', 'Durian', 'Avacado'];
var myArray2 = [];
myArray2.push(obj);
var key3 = "Random Fruits";
obj2[key3] = ['Kiwi', 'Pomegranate', 'Honeydew', 'Plum'];
var myArray3 = [];
myArray3.push(obj2);
var $header = $("<tr>"),
cols = 0,
bodyString = "";
$.each(obj, function(key, values) {
cols = Math.max(cols, values.length);
$header.append($('<th/>').text(key + ": " + values.length));
});
for (var i = 0; i < cols; i++) {
bodyString += '<tr>';
$.each(obj, function(key, values) {
bodyString += '<td>' +
(values[i] ? values[i] : "") +
'</td>';
});
bodyString += '</tr>';
}
$('.fruitsclass thead').html($header);
$('.fruitsclass tbody').html(bodyString);
var bodyString = '';
var headString = '';
$.each(obj2[key3], function(index) {
bodyString += ('<tr><td>' + obj2[key3][index] + '</td></tr>');
});
headString += ('<tr><th>' + 'Random Fruits' + '</th></tr>');
$('.fruityclass tbody').html(bodyString);
$('.fruityclass thead').html(headString);
$(document).ready(function() {
$("#fruityid td").click(function() {
getval(this);
});
});
function getval(cel) {
alert(cel.innerHTML);
}
.class {
font-family: Open Sans;
}
.center {
display: flex;
justify-content: center
}
.skillsTable th {
border-left: 1px solid #AAA5A4;
border-right: 1px solid #AAA5A4;
}
table {
float: left;
border-collapse: collapse;
width: 70%
}
td {
border-left: 1px solid #AAA5A4;
border-right: 1px solid #AAA5A4;
padding-top: 8px;
padding-left: 11px;
font-size: 15px;
}
th {
color: #0080ff;
font-weight: normal;
border-bottom: 1px solid #AAA5A4;
padding-bottom: 5px;
}
div {
margin-bottom: 50px;
}
<!DOCTYPE html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<meta charset="utf-8" />
<link rel="shortcut icon" href="//#" />
</head>
<body>
<div id="result"> </div>
<div class="center">
<table id="fruitsid" class="fruitsclass skillsTable class">
<thead></thead>
<tbody></tbody>
</table>
</div>
<div class="center">
<table id="fruityid" class="fruityclass skillsTable class">
<thead></thead>
<tbody></tbody>
</table>
</div>
</body>
</html>
Working on top of your code, changed listener function to remove the node:
function listener(obj) {
tbl = document.getElementById("fruitsTable");
if (tbl != null) {
for (var i = 0; i < tbl.rows.length; i++) {
for (var j = 0; j < tbl.rows[i].cells.length; j++)
tbl.rows[i].cells[j].onclick = function () {
getval(this);
data = this.innerHTML;
k1 = Object.keys(obj).find(k => obj[k].indexOf(data) >= 0 )
if (k1 != 'Random Fruits') {
key = 'Random Fruits'
} else {
key = 'Red Fruits';
}
index = obj[k1].indexOf(data);
obj[k1].splice(index, 1);
obj[key].push(data);
redraw(obj);
listener(obj);
};
}
}
}
It finds the relevant key and removes the element from that array, and pushes that into k2. Once done, it redraws the UI.
Fiddle - https://jsfiddle.net/wqzsn7ou/

Create a table from an object jquery/javascript

I am trying to implement the following.
A user enters a sentence into a textbox following which a table is created. An example would be this.
Input: "This is what I want to achieve"
Result:
Currently, based on the code I have there is an object that looks like this:
{t: ["this", "to"], i: ["is", "i"], w: ["what", "want"], a: ["achieve"]};
Below is the current code I have (also see jsfiddle here).
I am able to take the input string and create a table with a row which has the first letter of each word.
HTML
<textarea id="text-input" name="textarea" rows="5" cols="25">This is what I want to achieve</textarea>
<button class="calculate">Calculate</button>
<table>
<tbody>
<tr class="words-header"></tr>
</tbody>
</table>
Javascript
$(document).ready(function() {
$(".calculate").click(function() {
var result = {},
arr = [];
var array = $("#text-input").val().toLowerCase().split(" ");
for (var i = 0; i < array.length; i++) {
if (typeof result[array[i][0]] == 'undefined') {
result[array[i][0]] = [];
}
result[array[i][0]].push(arr[i]);
}
for (var key in result) {
$(".words-header").append("<td>" + key.toUpperCase() + "</td>");
}
});
});
I believe the final table should look like this if it helps:
<table>
<tr>
<td>A</td>
<td>I</td>
<td>T</td>
<td>W</td>
</tr>
<tr>
<td>achieve</td>
<td>is</td>
<td>this</td>
<td>what</td>
</tr>
<tr>
<td> </td>
<td>i</td>
<td>to</td>
<td>want</td>
</tr>
</table>
You can do it this way (Try it by clicking the Run code snippet button below):
var app = app || {};
(function() {
"use strict";
var result, arr;
app.initialize = {
init: function() {
app.splitWords.init();
}
};
app.splitWords = {
init: function() {
$(".calculate").click(function() {
result = [];
arr = $("#text-input").val().split(" ");
app.createMultiArray.init(arr);
});
}
};
app.createMultiArray = {
init: function(array) {
for (var i = 0; i < array.length; i++) {
var letter = array[i][0].toLowerCase();
if (typeof result[letter] == 'undefined') {
result[letter] = [];
}
result[letter].push(array[i]);
}
// I added this method
app.buildTable.init(result);
}
};
app.buildTable = {
init: function(result) {
var headers = Object.keys(result),
max_rows = 0,
rows_html = '';
headers.sort();
app.createHeaders.init(headers);
// Determine how many rows you'll need
for (var i = 0; i < headers.length; i++) {
if(result[headers[i]].length > max_rows) { max_rows = result[headers[i]].length; }
}
// Loop "max_rows" times
for (var i = 0; i < max_rows; i++) {
rows_html += '<tr>';
// Loop through all letters
for(var j = 0; j < headers.length; j++) {
rows_html += '<td>';
if(i < result[headers[j]].length) {
rows_html += result[headers[j]][i];
}
rows_html += '</td>';
}
rows_html += '</tr>';
}
$(".words-header").after(rows_html);
}
};
app.createHeaders = {
init: function(headers) {
// Empty the table in case of multiple tries
$(".words-header").parent().html('<tr class="words-header"></tr>');
for (var i = 0; i < headers.length; i++) {
$(".words-header").append("<td>" + headers[i].toUpperCase() + "</td>");
}
}
};
app.docOnReady = {
init: function() {
app.initialize.init();
}
};
$(document).ready(app.docOnReady.init);
})(jQuery);
#results-table table{ border-collapse: collapse; } #results-table td{ border: 1px solid #000; padding: .2em;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea id="text-input" name="textarea" rows="5" cols="25">This is what I want to achieve</textarea>
<button class="calculate">Calculate</button>
<div id="results-table">
<table>
<tbody>
<tr class="words-header"></tr>
</tbody>
</table>
</div>

Table should change the number of rows/columns?

Please see the below code, the table should change the number of rows based on input selected in the selected id option below, but only the first value of select id is read, and the number of rows are not changing based on the selection, can you please point out the mistake in my code ?
http://jsfiddle.net/uTY6n/14/
HTML:
<div id="scrollingDiv">
<select id="read">
<option value="1">1</option>
<option value="2">2</option></select>
<table id="contentTable" border="1">
<!-- Fill table programmatically -->
</table>
</div>
JAVASCRIPT:
function buildTable()
{
var myTable =document.getElementById("contentTable");
var j=document.getElementById("read").value;
var rows = [];
var cells = [];
for( var i = 0; i < j; i++ )
{
rows[i] = myTable.insertRow(i);
if(i%3==2)rows[i].addClass("everyrow");
cells[i] = [];
for( var x = 0; x < 3 ; x++ )
{
cells[i][x] =document.createElement((x==0)?"th":"td");
cells[i][x].innerHTML = (x==0)?"<input>":"<input>";
rows[rows.length - 1].appendChild(cells[i][x]);
}
}
}
buildTable();
CSS:
#scrollingDiv
{
border: 1px groove black;
height: 350px;
width: 350px;
background: #ffffff;
overflow: auto;
}
#contentTable
{
height: 350px;
width: 350px;
}
.every3rdrow{
border-bottom:3px solid black;
}
See this demo.
First, you need to attach an event listener to the <select>:
document.getElemenyById('read').addEventListener('change', buildTable);
Then, you need to make sure the table is emptied before it's rebuilt every time buildTable() is called:
function buildTable() {
var myTable =document.getElementById("contentTable");
var j=document.getElementById("read").value;
var rows = [];
var cells = [];
while (myTable.hasChildNodes()) {
myTable.removeChild(myTable.lastChild);
}
...
}
Hope this helps!
try
function buildTable() {
var myTable =document.getElementById("contentTable");
myTable.innerHTML = "";
var j=document.getElementById("read").value;
var rows = [];
var cells = [];
var myHtml = "";
for( var i = 0; i < j; i++ ) {
myHtml += "<tr>";
for( var x = 0; x < 3 ; x++ ){
myHtml += "<td></td>"
}
myHtml += "</tr>";
}
myTable.innerHTML = myHtml;
}
thats the general idea, also be sure to call this onChange of your select.

Categories