I'm creating a data grip for a project and I need to use Bootstrap Datepicker to the Date field.
The problem is that in the table only the first row (that is previously created) has the datepicker working.
If I create a second row, the datepicker isn't working.
Could you please help me? I would like to have the datepicker working fine in every created row and only on the Date field.
Below is my code:
function getElementsByClassName(c,el){
if(typeof el=='string'){
el=document.getElementById(el);
}
if(!el){
el=document;
}
if(el.getElementsByClassName){
return el.getElementsByClassName(c);
}
var arr=[],
allEls=el.getElementsByTagName('*');
for(var i=0;i<allEls.length;i++){
if(allEls[i].className.split(' ').indexOf(c)>-1){arr.push(allEls[i])}
}
return arr;
}
function killMe(el){
return el.parentNode.removeChild(el);
}
function getParentByTagName(el,tag){
tag=tag.toLowerCase();
while(el.nodeName.toLowerCase()!=tag){
el=el.parentNode;
}
return el;
}
// Delete table row
function delRow(){
killMe(getParentByTagName(this,'tr'));
}
// Insert table row
function addRow() {
var table = getParentByTagName(this,'table')
var lastInputs=table.rows.length>2?
table.rows[table.rows.length-2].getElementsByTagName('input'):[];
for(var i=0;i<lastInputs.length-1;i++){
if(lastInputs[i].value==''){return false;}
}
// New table row vars
var rowCount = table.rows.length;
var row = table.insertRow(rowCount-1);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.id = "expenseDate";
element1.type = "text";
element1.className="form-control datepicker";
cell1.appendChild(element1);
var cell2 = row.insertCell(1);
var element2 = document.createElement("input");
element2.type = "text";
element2.className="form-control";
cell2.appendChild(element2);
var cell3 = row.insertCell(2);
var element3 = document.createElement("input");
element3.type = "text";
element3.className="form-control";
cell3.appendChild(element3);
var cell4 = row.insertCell(3);
var element4 = document.createElement("input");
element4.type = "text";
element4.className="form-control";
cell4.appendChild(element4);
var cell5 = row.insertCell(4);
var element5 = document.createElement("input");
element5.type = "button";
element5.className="del btn btn-sm btn-danger";
element5.value='X';
element5.onclick=delRow;
cell5.appendChild(element5);
}
#ExpensesTable {
margin-top: 30px;
}
#ExpensesTable tr {
margin: 10px 0px 10px 0px;
}
#ExpensesTable td {
padding: 5px 5px 0px 5px;
}
#ExpensesTable th {
padding: 0px 5px 5px 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
</head>
<body>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="bootstrap-datepicker.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<div class="container">
<table id="ExpensesTable">
<tr>
<th>Date:</th>
<th>From:</th>
<th>To:</th>
<th>Nr. Km:</th>
</tr>
<tr>
<td><input class="add btn btn-sm btn-success" type="button" value="Add expense" id="AddExpense"/></td>
</tr>
</table>
</div>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="scripts.js"></script>
<script type="text/javascript" src="bootstrap-datepicker.min.js"></script>
<script type="text/javascript">
(function(){
var els=getElementsByClassName("add","ExpensesTable");
for(var i=0;i<els.length;i++){
els[i].onclick=addRow;
}
els[0].onclick();
})();
</script>
<script>
$('#expenseDate').datepicker({
});
</script>
</body>
</html>
try to leverage jquery to speed coding up and then you end up with like,, 4-5 lines of code to do what you need :)
cheers,
$('.dateP').datetimepicker();
$('.dupli').on( 'click', function(e){
var dup = $('.cpy').first().clone();
$('.table').append( dup );
$('.dateP').datetimepicker();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/3.1.4/js/bootstrap-datetimepicker.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/3.1.4/css/bootstrap-datetimepicker.css" rel="stylesheet"/>
<table class="table table-striped">
<tr>
<th>Event name</th>
<th>Date:</th>
<td><button type="submit" class="btn btn-default dupli">+</button></td>
</tr>
<tr class="cpy">
<td>
<input type="text" class="form-control" id="e1">
</td>
<td>
<div class='input-group dateP'>
<input type='text' class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</td>
</tr>
</table>
Related
Javascript jquery AutoComplate İnput not Working .I can try but not this. Add package link but AutoComplate İnput not Working.
I want only add pack after autocomplete input working. Only this..I think insertCell Hard this.I dont understend this. id ='dap'
$(function() {
var availableTags = [
"arta",
"barta",
"barta2",
];
$("#dap").autocomplete({
source: availableTags
});
});
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" />
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<title></title>
</head>
<body>
<form method="post" action="add.php">
<table id="table1">
<tr>
<br>
<td colspan="4"><a onclick="myFunction1()" style=" color: #000; margin-top: 10px"><i></i> Paket Ekle</a> <a onclick="myDeleteFunction1()" style="color: #000; margin-top: 10px"><i ></i> Paket Sil</a></td>
</tr>
<tr>
<td valign="bottom"><strong>GTIP No.</strong></td>
</tr>
<tr>
<td><input name="dap" type="text" style="width:90%; margin-top: 15px"></td>
<script>
var i = 1;
function myFunction1() {
var table = document.getElementById("table1");
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
cell1.innerHTML = "<input name='dap" + i + "' id='dap' type='text' style='width:90%;margin-top:15px;' >";
i++;
}
function myDeleteFunction1() {
document.getElementById("table1").deleteRow(-1);
}
</script>
</table>
</form>
</body>
</html>
You can use on to bind event on dynamically added element
$(function() {
var availableTags = [
"arta",
"barta",
"barta2",
];
$(document).on('keydown.autocomplete', '#dap', function() {
$(this).autocomplete({
source: availableTags
});
});
});
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" />
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<title></title>
</head>
<body>
<form method="post" action="add.php">
<table id="table1">
<tr>
<br>
<td colspan="4"><a onclick="myFunction1()" style=" color: #000; margin-top: 10px"><i></i> Paket Ekle</a> <a onclick="myDeleteFunction1()" style="color: #000; margin-top: 10px"><i ></i> Paket Sil</a></td>
</tr>
<tr>
<td valign="bottom"><strong>GTIP No.</strong></td>
</tr>
<tr>
<td><input name="dap" type="text" style="width:90%; margin-top: 15px"></td>
<script>
var i = 1;
function myFunction1() {
var table = document.getElementById("table1");
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
cell1.innerHTML = "<input name='dap" + i + "' id='dap' type='text' style='width:90%;margin-top:15px;' >";
i++;
}
function myDeleteFunction1() {
document.getElementById("table1").deleteRow(-1);
}
</script>
</table>
</form>
</body>
</html>
If you add a book you see the item added to the table with an awesome font fa-remove X. On hover I increase the size of icon but it slightly moves the text in the other td's. Is there a way to prevent this?
I found that if we wrap the link in a p tag and apply width:0 and margin-bottom:0 it will work but this seems like a hack. Is there a better way?
function Book(title,author,isbn){
this.title = title
this.author = author
this.isbn = isbn
}
function UI(){}
UI.addTr = function (book){
const table = document.getElementById("tbody");
const row = table.insertRow(-1);
const td0 = row.insertCell(0);
const td1 = row.insertCell(1);
const td2 = row.insertCell(2);
const td3 = row.insertCell(3);
td0.innerHTML = book.title;
td1.innerHTML = book.author;
td2.innerHTML = book.isbn;
td3.innerHTML = '';
const x = document.querySelectorAll('a')
//console.log(x,x[x.length - 1])
x[x.length - 1].addEventListener('click',myDelete)
}
UI.deleteTr = function(tr){
}
function myDelete(e){
//console.log(e.target)
}
const submit=document.getElementById('submit').addEventListener('click',mySubmit)
//console.log(document.getElementById('submit'))
function mySubmit(e){
e.preventDefault();
const inputs = Array.from(document.getElementsByClassName('inputs'))
let title, author, isbn
inputs.forEach((input,i) => {
switch(i){
case 0:
title = input.value
break
case 1:
author = input.value
break
case 2:
isbn = input.value
break
}
});
if(title == '' || author == '' || isbn == ''){
console.log('check inputs')
}else{
inputs.forEach((input) => {
input.value=''
})
const book = new Book(title,author,isbn)
UI.addTr(book)
}
}
#submit{
height: calc(1.5em + .75rem + 2px);
padding: .375rem .75rem;
font-size: 1rem;
font-weight: 400;
line-height: 1.5;
}
h1{
font-size:3rem!important;
}
#submit{
font-size:12px;
}
body{
letter-spacing:.1rem;
}
a, a:hover{
text-decoration:none!important;
color:red!important;
text-align:left;
}
a:hover{
font-size:larger;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title></title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
</head>
<body>
<div class="container w-75">
<h1 class="display-4 mb-4">Add Book</h1>
<form id="bookInputs">
<div class="form-group">
<label class='font-weight-bold' for="title">Title</label>
<input type="text" class="form-control inputs" id="title">
</div>
<div class="form-group">
<label class='font-weight-bold' for="author">Author</label>
<input type="text" class="form-control inputs" id="author">
</div>
<div class="form-group">
<label class='font-weight-bold' for="isbn">ISBN#</label>
<input type="text" class="form-control inputs" id="isbn">
</div>
<input id='submit' type='submit' value='submit' class='font-weight-bold w-100 bg-white border border-grey rounded'>
</form>
<table id='myTable' class="table table-striped">
<thead>
<tr>
<th class='border-top-0'>Title</th>
<th class='border-top-0'>Author</th>
<th class='border-top-0'>ISBN</th>
<th class='border-top-0'></th>
</tr>
</thead>
<tbody id='tbody'>
</tbody>
</table>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<!--<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>-->
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.6.0/dist/js/bootstrap.min.js" integrity="sha384-+YQ4JLhjyBLPDQt//I+STsc9iw4uQqACwlvpslubQzn4u2UU2UFM80nGisd026JF" crossorigin="anonymous"></script>
</body>
</html>
Setting width constraints solves it.
Simple case:
#myTable td { width: 25%}
function Book(title,author,isbn){
this.title = title
this.author = author
this.isbn = isbn
}
function UI(){}
UI.addTr = function (book){
const table = document.getElementById("tbody");
const row = table.insertRow(-1);
const td0 = row.insertCell(0);
const td1 = row.insertCell(1);
const td2 = row.insertCell(2);
const td3 = row.insertCell(3);
td0.innerHTML = book.title;
td1.innerHTML = book.author;
td2.innerHTML = book.isbn;
td3.innerHTML = '';
const x = document.querySelectorAll('a')
//console.log(x,x[x.length - 1])
x[x.length - 1].addEventListener('click',myDelete)
}
UI.deleteTr = function(tr){
}
function myDelete(e){
//console.log(e.target)
}
const submit=document.getElementById('submit').addEventListener('click',mySubmit)
//console.log(document.getElementById('submit'))
function mySubmit(e){
e.preventDefault();
const inputs = Array.from(document.getElementsByClassName('inputs'))
let title, author, isbn
inputs.forEach((input,i) => {
switch(i){
case 0:
title = input.value
break
case 1:
author = input.value
break
case 2:
isbn = input.value
break
}
});
if(title == '' || author == '' || isbn == ''){
console.log('check inputs')
}else{
inputs.forEach((input) => {
input.value=''
})
const book = new Book(title,author,isbn)
UI.addTr(book)
}
}
/******/
#myTable td{width:25%}
/******/
#submit{
height: calc(1.5em + .75rem + 2px);
padding: .375rem .75rem;
font-size: 1rem;
font-weight: 400;
line-height: 1.5;
}
h1{
font-size:3rem!important;
}
#submit{
font-size:12px;
}
body{
letter-spacing:.1rem;
}
a, a:hover{
text-decoration:none!important;
color:red!important;
text-align:left;
}
a:hover{
font-size:larger;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title></title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
</head>
<body>
<div class="container w-75">
<h1 class="display-4 mb-4">Add Book</h1>
<form id="bookInputs">
<div class="form-group">
<label class='font-weight-bold' for="title">Title</label>
<input type="text" class="form-control inputs" id="title">
</div>
<div class="form-group">
<label class='font-weight-bold' for="author">Author</label>
<input type="text" class="form-control inputs" id="author">
</div>
<div class="form-group">
<label class='font-weight-bold' for="isbn">ISBN#</label>
<input type="text" class="form-control inputs" id="isbn">
</div>
<input id='submit' type='submit' value='submit' class='font-weight-bold w-100 bg-white border border-grey rounded'>
</form>
<table id='myTable' class="table table-striped">
<thead>
<tr>
<th class='border-top-0'>Title</th>
<th class='border-top-0'>Author</th>
<th class='border-top-0'>ISBN</th>
<th class='border-top-0'></th>
</tr>
</thead>
<tbody id='tbody'>
</tbody>
</table>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<!--<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>-->
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.6.0/dist/js/bootstrap.min.js" integrity="sha384-+YQ4JLhjyBLPDQt//I+STsc9iw4uQqACwlvpslubQzn4u2UU2UFM80nGisd026JF" crossorigin="anonymous"></script>
</body>
</html>
This question already has answers here:
What is DOM Event delegation?
(10 answers)
Closed 4 years ago.
I have a table in which an input control calls a java script event
oninput="this.value=this.value.replace(/[^0-9]/g,'');
By Clicking on Add Row new Row is being inserted but i want to call this event on new row as well . This event is to stop except positive whole numbers
using the following code.
<html>
<head>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/7.0.0/normalize.css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
</head>
<body>
<input type="hidden" id="minsize" value="1">
<div class="">
<table id="mintable" class="table table-bordered table-striped stripe hover row-border">
<thead class="div-head">
<tr>
<th><b>Roll No</b></th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" id='rollno0' oninput="this.value=this.value.replace(/[^0-9]/g,'');" class="form-control"></td>
</tr>
</tbody>
</table>
<input type="hidden" name="minRows" id="minRows" value='1'>
<input type="hidden" id="sizemin" name="sizemin" value='1' />
</div>
<input type="submit" data-toggle="tooltip" title="Insert new horizon
" data-placement="top" class="btn btn-primary" id="button" value="Add Row" onClick="addRow()" />
<script>
function addRow() {
var table = document.getElementById("mintable");
var rowCount = parseInt(document.getElementById("minRows").value);
var rowInsert = parseInt(document.getElementById("sizemin").value);
var row = table.insertRow(rowInsert + 1);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "text";
element1.id = "rollnoo" + (rowCount);
element1.className = "form-control";
cell1.appendChild(element1);
rowCount = parseInt(rowCount)+ 1;
document.getElementById("minRows").value = rowCount;
document.getElementById("sizemin").value =
parseInt(document.getElementById("sizemin").value) + 1;
}
</script>
</body>
</html>
Try the following syntax to add event handler to newly created element:
element1.oninput = function() {
this.value = this.value.replace(/[^0-9]/g,'');
}
<html>
<head>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/7.0.0/normalize.css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
</head>
<body>
<input type="hidden" id="minsize" value="1">
<div class="">
<table id="mintable" class="table table-bordered table-striped stripe hover row-border">
<thead class="div-head">
<tr>
<th><b>Roll No</b></th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" id='rollno0' oninput="this.value=this.value.replace(/[^0-9]/g,'');" class="form-control"></td>
</tr>
</tbody>
</table>
<input type="hidden" name="minRows" id="minRows" value='1'>
<input type="hidden" id="sizemin" name="sizemin" value='1' />
</div>
<input type="submit" data-toggle="tooltip" title="Insert new horizon
" data-placement="top" class="btn btn-primary" id="button" value="Add Row" onClick="addRow()" />
<script>
function addRow() {
var table = document.getElementById("mintable");
var rowCount = parseInt(document.getElementById("minRows").value);
var rowInsert = parseInt(document.getElementById("sizemin").value);
var row = table.insertRow(rowInsert + 1);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "text";
element1.id = "rollnoo" + (rowCount);
element1.className = "form-control";
element1.oninput = function() {
this.value = this.value.replace(/[^0-9]/g,'');
}
cell1.appendChild(element1);
rowCount = parseInt(rowCount)+ 1;
document.getElementById("minRows").value = rowCount;
document.getElementById("sizemin").value =
parseInt(document.getElementById("sizemin").value) + 1;
}
</script>
</body>
</html>
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>
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!