Hello I am new to website development (started a couple of days ago).
I have some programming experience using Python and C#.
I have been trying to generate an HTML table using JS and apply it a Bootstrap css style.
I can't seem to get it to work.
What I get:
What I want:
I hope to get something that styles like this (simplified from: w3schools)
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2>Basic Table</h2>
<p>The .table class adds basic styling (light padding and only horizontal dividers) to a table:</p>
<table class="table">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
</tr>
<tr>
<td>John</td>
<td>Doe</td>
<td>john#example.com</td>
</tr>
</table>
</div>
</body>
</html>
My html page looks like this:
<!DOCTYPE html>
<html>
<head>
<title>CSVParser</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<script type="text/javascript" src="../scripts/csvToHtml.js"></script>
<form onsubmit="return processFile();" action="#" name="myForm" id="aForm" method="POST">
<input type="file" id="myFile" name="myFile"><br>
<input type="submit" name="submitMe" value="Process File">
</form>
<table id="myTable" class="table"></table>
</div>
</body>
</html>
and the JS script is:
function processFile() {
var fileSize = 0;
var theFile = document.getElementById("myFile").files[0];
if (theFile) {
var table = document.getElementById("myTable");
var headerLine = "";
var myReader = new FileReader();
myReader.onload = function(e) {
var content = myReader.result;
var lines = content.split("\r");
for (var count = 0; count < lines.length; count++) {
var row = document.createElement("tr");
var rowContent = lines[count].split(",");
for (var i = 0; i < rowContent.length; i++) {
if (count == 0) {
var cellElement = document.createElement("th");
} else {
var cellElement = document.createElement("td");
}
var cellContent = document.createTextNode(rowContent[i]);
cellElement.appendChild(cellContent);
row.appendChild(cellElement);
}
myTable.appendChild(row);
}
}
myReader.readAsText(theFile);
}
return false;
}
The csv data file I load looks like this:
TestA,TestB,TestC,TestD
Alpha,0.551608445,0.807554763,54.8608682
Beta,0.191220409,0.279946678,57.55254144
This is the generated HTML table from the JS:
<table id="myTable" class="table">
<tr>
<th>TestA</th>
<th>TestB</th>
<th>TestC</th>
<th>TestD</th>
</tr>
<tr>
<td>Alpha</td>
<td>0.551608445</td>
<td>0.807554763</td>
<td>54.8608682</td>
</tr>
<tr>
<td>Beta</td>
<td>0.191220409</td>
<td>0.279946678</td>
<td>57.55254144</td>
</tr>
<tr>
<td></td>
</tr>
</table>
You are missing a <tbody> element around all the <tr> Elements. thats it. if you insert this additionally you are fine with your layout.
I've changed your code quite a bit but here is a working example:
<!DOCTYPE html>
<html>
<head>
<title>CSVParser</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<form action="#" name="myForm" id="aForm" method="POST">
<input type="file" id="myFile" name="myFile"><br>
<input type="button" name="submitMe" value="Process File" onclick="processFile();">
</form>
<table id="myTable" class="table"></table>
</div>
</body>
<script type="text/javascript">
function processFile() {
var fileSize = 0;
var theFile = document.getElementById("myFile").files[0];
if (theFile) {
var table = document.getElementById("myTable");
var headerLine = "";
var myReader = new FileReader();
myReader.onload = function(e) {
var content = myReader.result;
var lines = content.split("\r");
var tbody = document.createElement("tbody");
for (var count = 0; count < lines.length; count++) {
var row = document.createElement("tr");
var rowContent = lines[count].split(",");
for (var i = 0; i < rowContent.length; i++) {
if (count == 0) {
var cellElement = document.createElement("th");
} else {
var cellElement = document.createElement("td");
}
var cellContent = document.createTextNode(rowContent[i]);
cellElement.appendChild(cellContent);
row.appendChild(cellElement);
}
tbody.appendChild(row);
}
table.appendChild(tbody);
}
myReader.readAsText(theFile);
}
return false;
}
</script>
</html>
Working example without having to upload a file
<!DOCTYPE html>
<html>
<head>
<title>CSVParser</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<form action="#" name="myForm" id="aForm" method="POST">
<textarea id="myFile" name="myFile">TestA,TestB,TestC,TestD
Alpha,0.551608445,0.807554763,54.8608682
Beta,0.191220409,0.279946678,57.55254144</textarea><br>
<input type="button" name="submitMe" value="Process File" onclick="processFile();">
</form>
<table id="myTable" class="table"></table>
</div>
</body>
<script type="text/javascript">
function processFile() {
var table = document.querySelector("#myTable");
var content = $("#myFile").val();
var lines = content.split("\n");
var tbody = document.createElement("tbody");
for (var count = 0; count < lines.length; count++) {
var row = document.createElement("tr");
var rowContent = lines[count].split(",");
for (var i = 0; i < rowContent.length; i++) {
if (count == 0) {
var cellElement = document.createElement("th");
} else {
var cellElement = document.createElement("td");
}
var cellContent = document.createTextNode(rowContent[i]);
cellElement.appendChild(cellContent);
row.appendChild(cellElement);
}
tbody.appendChild(row);
}
table.appendChild(tbody);
return false;
}
</script>
</html>
ALSO! You are using myTable.appendChild(row); in your code although you've never initialized any myTable variable.
Load your js script just before the </body> end tag.
Now you are loading the JavaScript before the browser has read all your tags and by then it can't find the elements you are querying in your script.
<body>
<div class="container">
<form onsubmit="return processFile();" action="#" name="myForm" id="aForm" method="POST">
<input type="file" id="myFile" name="myFile"><br>
<input type="submit" name="submitMe" value="Process File">
</form>
<table id="myTable" class="table"></table>
</div>
<!-- Here's the difference -->
<script type="text/javascript" src="../scripts/csvToHtml.js"></script>
</body>
Related
Good afternoon, I'm a beginner, I'm having trouble getting information from a table that consumes data from an api.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="main.js"></script>
<title>Document</title>
</head>
<body onload="apendeOnClick()">
<table id="tablerow">
<caption>Alien football stars</caption>
<thead>
<tr>
<th>DATA</th>
<th>TELEFONE</th>
<th>RAMAL</th>
<th>DESCRIÇÃO</th>
<th>ACÕES</th>
</tr>
</thead>
<tbody id="table_body">
</tbody>
</table>
<script>
</script>
</body>
</html>
My code is this, it feeds the table normally, but I would like when the person clicks on the row button to display the information in the alert.
main.js
fetch("https://my-json-server.typicode.com/lfnoleto/api-fake/contact").then((data) => {
return data.json()
}).then((Objectdata) => {
//console.log(Objectdata[0].data)
let tabelaData = ""
Objectdata.map((values)=>{
tabelaData += `<tr>
<td>${values.data}</td>
<td>${values.tefone}</td>
<td>${values.ramal}</td>
<td>${values.descricao}</td>
<td><button id="butao" class="btn btn-success" ><i class="fa fa-phone"></button></td>
</tr>`
})
document.getElementById("table_body").innerHTML = tabelaData
innerHTML = tabelaData
})
function apendeOnClick(){
const table = document.getElementById("tablerow")
console.log(table)
if (table) {
for (var i = 0; i < table.rows.length; i++) {
table.rows[i].childNodes[5].childNodes[1].onclick = function() {
tableText(this);
};
}
}
}
function tableText(tableRow) {
let telefone = tableRow.childNodes[1].innerHTML;
let ramal = tableRow.childNodes[2].innerHTML;
let obj = {'telefone': telefone, 'ramal': ramal};
console.log(obj);
}
I hope that when the person clicks on the telephone icon, he displays the extension and telephone information
you can use data attribute to store extension info or other information.
<button id="butao" data-extension="123" class="btn btn-success" >
in javascript :
const button = document.querySelector('button');
button.dataset.extention // "123"
a good references:
https://www.w3schools.com/tags/att_data-.asp
https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes
I am creating a website that allows the user to create a contact, and there is a search box that allows the user to search in the created contacts.
The problem is when the user creates contact and searches, the search box does not work.
The code is running well when I create the contacts manually in the HTML file. It means that the search box only searches in the HTML file, and doesn't search in the newly created contacts by the innerHTML code by JavaScript.
And please answer me with JAVASCRIPT code, not jQuery.
This is my code, only HTML and JAVASCRIPT , no css :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Javascript Project 11</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<form id="myForm">
<input id="create" type="text" placeholder="create">
<button id="btn" type="submit">Submit</button>
</form>
<br>
<input id="search" placeholder="search..." type="text">
<div id="demo">
<!--HERE IS YOUR LIST OF CONTACTS-->
<ul id="names">
</ul>
</div>
<script src="js/main.js"></script>
</body>
</html>
Javascript code:
//CREATE NEW CONTACT
//CREATE NEW LI I MEAN
document.getElementById('myForm').addEventListener('submit', createContact)
function createContact(e) {
//input
var menuItem = document.getElementById('menuItem');
var newName = document.getElementById('create').value;
var demo = document.getElementById('demo');
demo.innerHTML +=
'<li class=menuItem>' + newName + '</li>';
e.preventDefault();
}
//Search Filter
var searchBox = document.getElementById('search');
searchBox.addEventListener('keyup', filter);
function filter() {
var ul = document.getElementById('names');
var li = ul.querySelectorAll('li.menuItem');
var searchBoxValue = document.getElementById('search').value.toUpperCase();
for (var i = 0; i < li.length; i++) {
var newName = document.getElementById('create').value;
var a = li[i].getElementsByTagName('a')[0];
if (a.innerHTML.toUpperCase().indexOf(searchBoxValue) > -1) {
li[i].style.display = '';
}
else {
li[i].style.display = 'none';
}
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Javascript Project 11</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<form id="myForm">
<input id="create" type="text" placeholder="create">
<button id="btn" type="submit">Submit</button>
</form>
<br>
<input id="search" placeholder="search..." type="text">
<div id="demo">
<!--HERE IS YOUR LIST OF CONTACTS-->
<ul id="names">
</ul>
</div>
<script src="js/main.js"></script>
</body>
</html>
You append new items to <div id="demo"> instead of <ul id="names">. It should be like this:
var names = document.getElementById('names');
names.innerHTML += '<li class="menuItem">' + newName + '</li>';
//CREATE NEW CONTACT
//CREATE NEW LI I MEAN
document.getElementById('myForm').addEventListener('submit', craeteContact)
function craeteContact(e) {
//input
var menuItem = document.getElementById('menuItem');
var newName = document.getElementById('create').value;
var names= document.getElementById('names');
names.innerHTML +=
'<li class="menuItem">' + newName + '</li>';
e.preventDefault();
}
//Search Filter
var searchBox = document.getElementById('search');
searchBox.addEventListener('keyup', filter);
function filter() {
var ul = document.getElementById('names');
var li = ul.querySelectorAll('li.menuItem');
var searchBoxValue = document.getElementById('search').value.toUpperCase();
for (var i = 0; i < li.length; i++) {
var newName = document.getElementById('create').value;
var a = li[i].getElementsByTagName('a')[0];
if (a.innerHTML.toUpperCase().indexOf(searchBoxValue) > -1) {
li[i].style.display = '';
}
else {
li[i].style.display = 'none';
}
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Javascript Project 11</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<form id="myForm">
<input id="create" type="text" placeholder="create">
<button id="btn" type="submit">Submit</button>
</form>
<br>
<input id="search" placeholder="search..." type="text">
<div id="demo">
<!--HERE IS YOUR LIST OF CONTACTS-->
<ul id="names">
</ul>
</div>
<script src="js/main.js"></script>
</body>
</html>
it's because you place li elements in #demo instead of #names
you should use console.log() to debug
Use an array to save names and then search the array. why you get data from UI everytime
var searchBox = document.getElementById('search');
searchBox.addEventListener('keyup', filter);
document.getElementById('myForm').addEventListener('submit', craeteContact)
var names = [];
function craeteContact(e) {
var menuItem = document.getElementById('menuItem');
var newName = document.getElementById('create').value;
var demo = document.getElementById('demo');
names.push(newName.toUpperCase()); // add new name to array
demo.innerHTML += '<li class=menuItem>' + newName + '</li>';
e.preventDefault();
}
function filter() {
var searchValue = searchBox.value.toUpperCase();
for (var i = 0; i < names.length; i++) {
if (names[i].indexOf(searchValue) > -1) {
console.log("found");
}
else {
console.log("not found");
}
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Javascript Project 11</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<form id="myForm">
<input id="create" type="text" placeholder="create">
<button id="btn" type="submit">Submit</button>
</form>
<br>
<input id="search" placeholder="search..." type="text">
<div id="demo">
<!--HERE IS YOUR LIST OF CONTACTS-->
<ul id="names">
</ul>
</div>
<script src="js/main.js"></script>
</body>
</html>
I have made a function test tool for my company app using html/css/javascript/node.js/express/tablesorter.
My test tool is successfully performed the function tests.
My table style is from opensource 'Tablesorter'.
This is edit screen. The file is .ejs format. So, Node.js server render the file to html dynamically.
But, I wonder how to insert the row additionally in this table. So, I searched to solve the problem and got some solution like below.
for (var i in rList) {
var table = document.getElementById("ID_Table");
var row = table.insertRow(-1);
var cell1 = row.insertCell(-1);
var cell2 = row.insertCell(-1);
var list = rList[i].split(" ");
cell1.innerHTML = list[0];
cell2.innerHTML = list[1];
}
But, this way is incomplete. The result is like this.
The 'tablesorter' style is not applied to additional rows. I don't know how to solve this.
<!DOCTYPE html>
<html>
<head>
<!-- Character Set -->
<meta charset="utf-8">
<!-- Title -->
<title><%= title %></title>
<!-- Style -->
<link rel='stylesheet' href='/stylesheets/style.css'/>
<!-- JS -->
<script src="/javascripts/indexCore.js"></script>
<!-- jQuery -->
<script src="/opensources/tablesorter/docs/js/jquery-latest.min.js"></script>
<script src="/opensources/tablesorter/docs/js/jquery-ui.min.js"></script>
<!-- Tablesorter: theme -->
<link class="theme default" rel="stylesheet" href="/opensources/tablesorter/css/theme.default.css">
<link class="theme blue" rel="stylesheet" href="/opensources/tablesorter/css/theme.blue.css">
<link class="theme green" rel="stylesheet" href="/opensources/tablesorter/css/theme.green.css">
<link class="theme grey" rel="stylesheet" href="/opensources/tablesorter/css/theme.grey.css">
<link class="theme ice" rel="stylesheet" href="/opensources/tablesorter/css/theme.ice.css">
<link class="theme black-ice" rel="stylesheet" href="/opensources/tablesorter/css/theme.black-ice.css">
<link class="theme dark" rel="stylesheet" href="/opensources/tablesorter/css/theme.dark.css">
<link class="theme dropbox" rel="stylesheet" href="/opensources/tablesorter/css/theme.dropbox.css">
<link class="theme metro-dark" rel="stylesheet" href="/opensources/tablesorter/css/theme.metro-dark.css">
<!-- Tablesorter script: required -->
<script src="/opensources/tablesorter/js/jquery.tablesorter.js"></script>
<script src="/opensources/tablesorter/js/widgets/widget-filter.js"></script>
<script src="/opensources/tablesorter/js/widgets/widget-stickyHeaders.js"></script>
<script id="js">
$(function(){
/* make second table scroll within its wrapper */
$('#ID_Table').tablesorter({
widthFixed : true,
headerTemplate : '{content} {icon}', // Add icon for various themes
widgets: [ 'zebra', 'stickyHeaders', 'filter' ],
widgetOptions: {
// jQuery selector or object to attach sticky header to
stickyHeaders_attachTo : '.wrapper' // or $('.wrapper')
}
});
$("#ID_Table tbody").click(function () {
//$(this).addClass('selected').siblings().removeClass('selected');
//alert('a');
});
});
</script>
<script>
$(function() { //이 부분은 렌더링 되자마자 실행되는 부분
window.includeCaption = true;
$('.caption').on('click', function(){
includeCaption = !includeCaption;
$(this).html( '' + includeCaption );
$('#ID_Table').each(function(){
if (this.config) {
this.config.widgetOptions.stickyHeaders_includeCaption = includeCaption;
this.config.widgetOptions.$sticky.children('caption').toggle(includeCaption);
}
});
});
// removed jQuery UI theme because of the accordion!
$('link.theme').each(function(){ this.disabled = true; });
var themes = 'dropbox blue green grey ice black-ice dark default metro-dark', //테마 순서
i, o = '', t = themes.split(' ');
for (i = 0; i < t.length; i++) {
o += '<option value="' + t[i] + '">' + t[i] + '</option>';
}
$('select:first')
.append(o)
.change(function(){
var theme = $(this).val().toLowerCase(),
// ui-theme is added by the themeswitcher
files = $('link.theme').each(function(){
this.disabled = true;
})
files.filter('.' + theme).each(function(){
this.disabled = false;
});
$('table')
.removeClass('tablesorter-' + t.join(' tablesorter-'))
.addClass('tablesorter-' + (theme === 'black-ice' ? 'blackice' : theme) );
}).change();
});
</script>
</head>
<body>
<div id="header">
<h1><%= title %></h1>
<p>Welcome to <%= title %></p>
Main
Edit
Blank
<hr/>
</div>
<div id="wrap">
<div id="Main_Screen">
<input type="button" value="로딩" id="btn" onclick="dynamicLoadScript_Main('/temps/MainScript.js', '/temps/WrapScript.js')"></input>
<input type="button" value="수행" id="btn1" onclick="Automation()"></input>
<button type="button">결과 리스트 출력</button>
</div>
<div id="List_Screen" class="narrow-block wrapper">
Theme: <select></select>
<table id="ID_Table" class="tablesorter" border="0" cellpadding="0" cellspacing="1">
<thead>
<tr>
<th>Function</th>
<th>Result</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
</html>
This is my .ejs File.
And, this is printResult Function in indexCore.js.
function printResult(){
var rList = resultList.split('\n');
for (var i in rList) {
var table = document.getElementById("ID_Table");
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var list = rList[i].split(" ");
cell1.innerHTML = list[0];
cell2.innerHTML = list[1];
}
}
You can edit and apply your logic at the .ejs file directly at your backend as your client side solution seems to be run after table being initialized by Tablesorter. You can also try to implement your client side solution adding the rows to table first then initialize Tablesorter. Good Luck!
I wish to have the array of inputs to be remembered using the local storage feature of html5. At the moment i can populate the array with weight inputs but once i refresh they disappear. Could anyone help me with this.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Home Fitness</title>
<link type="text/css" rel="stylesheet" href="styles.css" />
<script>
var arrayX =10;
var arrayY =2;
var array=new Array(arrayX);
var arrayIndex=0;
for (x=0; x<array.length; x++)
{
array [x] = new Array(arrayY);
}
function insert(val1, val2){
if (arrayIndex >= arrayX)
{
alert("Recent Entries is Full");
return false;
}
array[arrayIndex][0]=val1;
array[arrayIndex][1]=val2;
arrayIndex++;
document.getElementById('weight1').value = '';
document.getElementById('unit').value = '';
}
function show() {
var string='<b>Weight Entries</b><br>';
for(i = 0; i < array.length; i++)
{
string+=''+array[i][0]+' '+array[i][1]+'<br>';
}
if(array.length > 0)
document.getElementById('myDiv').innerHTML = string;
}
</script>
</head>
<body>
<header>
<h1>Weight Tracker</h1>
</header>
<article>
<h2>Weight Input</h2>
<p>Please enter your current weight below and submit.</p>
</article>
<form name="form1">
<table align="center" width="407">
<tr>
<td width="154" align="right"><b>Weight</b> </td>
<td width="9"><b> :</b></td>
<td width="224">
<input type="integer" name="weight" id="weight1"/></td>
<tr>
<td width="154" align="right"><b>Unit (KG,Ibs, Stone)</b></td>
<td width="9"><b> :</b></td>
<td width="224">
<input type="integer" name="unit" id="unit"/></td>
</tr>
</table>
</br>
<table width="407">
<input type="button" value="Submit Weight"
onclick="insert(this.form.weight.value,this.form.unit.value);"/>
<input type="button" value="Recent Entries"
onclick="show();"/>
</table>
</form>
</br>
<div id="myDiv"></div>
<nav>
<ul>
<li>home</li>
</ul>
</nav>
just stringify your array and save it to localStorage when you are done.
localStorage["array"] = JSON.stringify(array)
<!doctype html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<title>Template Index</title>
<style>
</style>
</head>
<body>
<div>
<input id="name"/>
</div>
<script>
window.addEventListener("beforeunload", function () {
var name = document.getElementById("name");
localStorage.setItem("name", name.value);
}, false);
window.addEventListener("load", function (){
var name = document.getElementById("name");
name.value = localStorage.getItem("name");
}, false);
</script>
</body>
</html>
the core code is above. you can make your own logic to accomplish your goal
https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage
I have a jsp which onload calls a js in which a table is created dynamically.
The situation is that I have never worked on jquery earlier, all I know is javascript.
I made two scenarios:
case one : when I create static table on the jsp page itself it works flawlessly.
case two : when I try to load the same table which is created by dynamic javascript it fails.
Case I Working code
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<script src="../js/jquery.js"></script>
<script type="text/javascript" src="../js/createDynamicTable.js"></script>
<script type="text/javascript" src="../js/jquery.dataTables.js"></script>
<script>
$(document).ready(function() {
$('#testTable').dataTable();
});
</script>
</head>
<body>
<div id="tableDataDiv">
<table id="testTable">
<thead>
<th>h1</th>
<th>h2</th>
<th>h3</th>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>4</td>
<td>5</td>
<td>6</td>
</tr>
<tr>
<td>7</td>
<td>8</td>
<td>9</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
Case II Not Working code
jsp code
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<script src="../js/jquery.js"></script>
<script type="text/javascript" src="../js/createDynamicTable.js"></script>
<script type="text/javascript" src="../js/jquery.dataTables.js"></script>
<script>
$(document).ready(function() {
$('#testTable').dataTable();
});
</script>
</head>
<body onload="getTableData();">
<div id="tableDataDiv">
</div>
</body>
</html>
js code
function getTableData(){
var tableDataDivObj = document.getElementById("tableDataDiv");
var tableObj = document.createElement("table");
tableObj.id = 'testTable';
// header
var theadObj = document.createElement("thead");
var thObj = document.createElement("th");
thObj.innerHTML = 'h1';
theadObj.appendChild(thObj);
thObj = document.createElement("th");
thObj.innerHTML = 'h2';
theadObj.appendChild(thObj);
thObj = document.createElement("th");
thObj.innerHTML = 'h3';
theadObj.appendChild(thObj);
tableObj.appendChild(theadObj);
// body
var tbodyObj;
var trObj;
var tdObj;
tbodyObj = document.createElement("tbody");
var count = 1;
for(i = 0; i < 3; i++){
trObj = document.createElement("tr");
for(j = 0; j < 3; j++){
tdObj = document.createElement("td");
tdObj.innerHTML = count;
trObj.appendChild(tdObj);
count++;
}
tbodyObj.appendChild(trObj);
}
tableObj.appendChild(tbodyObj);
tableDataDivObj.appendChild(tableObj);
}
Once the table is created dynamically, we append it to the div on the jsp page.
Kindly suggest any modification, suggestions so that I can get this code work.
this is just an example I have created of my real application .
which involves complete mvc, where table data is retrived from the service methods and dao files. I am able to get the data into the table(I made sure after getting an alert on jsp page). I am not able to use datatable on the id of the table.
Thanks in advance!
When your dataTables initialization is run, the table doesn't exist yes. You can fix by moving the $('#testTable').dataTable(); after the table has been initialized.
$(tableObj).dataTable();
at the end of the getTableData function (which should be defined in your $(document).ready callback.
Yon can add datatable to your dynamically created table in javascript.Code is as follows:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.2.min.js"></script>
<script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/jquery.dataTables.min.js"></script>
function createTable(){
var myTableDiv = document.getElementById("box");
var table = document.createElement('TABLE');
table.id='tableId'
table.border='1';
var header = table.createTHead();
var row = header.insertRow(0);
var cell = row.insertCell(0);
var cell1 = row.insertCell(1);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(1);
cell.innerHTML = "<b>Name</b>";
cell1.innerHTML = "<b>Age</b>";
cell2.innerHTML = "<b>Email</b>";
cell3.innerHTML = "<b>address</b>";
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);
$("#tableId").dataTable();
}
</head>
<body>
<input type="button" onclick="createTable();" value="CreateTable" /></br>
<div id="box">
</div>
</body>
</html>
Please call jquery method once your table get created by dynamic javascript.
You can find example here how to create dynamically:
http://datatables.net/release-datatables/examples/data_sources/js_array.html