My table is given below.
i want to find out whenever click event handler calls on
<!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.1.1/jquery.min.js"></script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function() {
var t = $('#example').DataTable();
var counter = 1;
t.row.add( [
"<input type='checkbox'>",
"<a href='#'>"+ counter+'.1' +"</a>",
counter +'.3',
counter +'.4',
counter +'.5',
counter +'.6'
]).draw( true );
counter++;
t.row.add( [
"<input type='checkbox'>",
"<a href='#'>"+ counter+'.1' +"</a>",
counter +'.3',
counter +'.4',
counter +'.5',
counter +'.6'
]).draw( false );
counter++;
$("tr").click(function(context) {
var value = context.currentTarget.innerHTML;
$(".modal-body").after(value);
$("#11").prop("hidden",false);
});
$(".btn").click(function() {
$(".modal-body").empty();
$("#11").prop("hidden",true);
});
});
</script>
</head>
<body>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Sr No.</th>
<th name="aa">Modal View</th>
<th>Label1</th>
<th>Label2</th>
<th>Label3</th>
<th>Label4</th>
</tr>
</thead>
</table>
<div id="11" hidden="true" class="modal-content">
<div class="modal-header">
<h4 class="modal-title"></h4>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</body>
</html>
Here when on click of tr i am finding that modal view is opening but it is opening on click of any column of that row.
Also if i will not close that modal than it will append all other row data to that modal.i don't want that as well.
Given below may be the closest answer you want and also modern way of doing it. You can refer this link for further details of the way of creating modal dynamically.
$(document).ready(function() {
var t = $('#example').DataTable();
for (i = 1; i <= 10; i++) {
t.row.add([
'<input type="checkbox">',
'' + i + '.1' + '',
i + '.3',
i + '.4',
i + '.5',
i + '.6'
]).draw(true);
}
});
function showModal(rowid) {
BootstrapDialog.show({
title: 'Title goes here.',
message: function() {
var msg = '';
msg += '<table>';
msg += ' <thead>';
msg += ' <tr>' + $('#example thead tr').html() + '</tr>';
msg += ' </thead>';
msg += ' <tbody>';
msg += ' <tr>' + $('#example tbody tr:nth-child(' + rowid + ')').html() + '</tr>';
msg += ' </tbody>';
msg += '</table>';
return msg;
},
buttons: [{
label: 'Close',
action: function(dialog) {
dialog.close();
}
}]
});
}
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap3-dialog/1.34.7/css/bootstrap-dialog.min.css">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap3-dialog/1.34.7/js/bootstrap-dialog.min.js"></script>
<script src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Sr No.</th>
<th name="aa">Modal View</th>
<th>Label1</th>
<th>Label2</th>
<th>Label3</th>
<th>Label4</th>
</tr>
</thead>
</table>
Related
I have been trying to resolve this but I don't know what I'm missing.
I have a table where I get API information using fetch. I want the input to filter the users as I type on it. This is what I have so far, if it's possible I want to keep using filter() and pure Javascript. I believe my problem is not knowing how to access the information in the rows
const listItems = document.querySelectorAll("#data");
This line seems not to work the way I want it to. Here is the code:
fetch(
"https://gist.githubusercontent.com/SuecoMarcus/a77af69f0e84c3125a5c0cf43a3ac41b/raw/918cd058b7e2286a36e79643c63a5ebca097d7c8/users.json"
).then((response) => {
response.json().then((data) => {
let row = "";
data.forEach((itemData) => {
row += "<tr>";
row += "<td>" + itemData.id + "</td>";
row += "<td>" + itemData.firstname + "</td>";
row += "<td>" + itemData.lastname + "</td>";
row += "<td>" + itemData.age + "</td></tr>";
});
document.querySelector("#data").innerHTML = row;
});
});
document.querySelector("#search-input").addEventListener("input", filterTable);
function filterTable(e) {
const searchInput = document.querySelector("#search-input");
const filter = searchInput.value.toLowerCase();
const listItems = document.querySelectorAll("#data");
listItems.forEach((item) => {
let text = item.textContent;
if (text.toLowerCase().includes(filter.toLowerCase())) {
item.style.display = "";
} else {
item.style.display = "none";
}
});
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
<title>Hack Academy - Proyecto Base</title>
<!-- CSS de Bootstrap -->
<link
href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.0/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-KyZXEAg3QhqLMpG8r+8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We"
crossorigin="anonymous"
/>
<!-- CSS Propio -->
<link rel="stylesheet" href="css/styles.css" />
</head>
<body>
<div class="container mt-5" id="app">
<input
style="width: inherit"
id="search-input"
placeholder="Ingresar texto a buscar...
"
type="search"
/>
<table class="table table-search">
<thead>
<tr>
<th>ID</th>
<th>Nombre</th>
<th>Apellido</th>
<th>Edad</th>
</tr>
</thead>
<tbody id="data"></tbody>
</table>
</div>
<!-- JS de Bootstrap -->
<script
src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.0/dist/js/bootstrap.bundle.min.js"
integrity="sha384-U1DAWAznBHeqEIlVSCgzq+c9gqGAJn5c/t99JyeKa9xxaYpSvHU5awsuZVVFIhvj"
crossorigin="anonymous"
></script>
<!-- JS Propio -->
<script src="js/app.js"></script>
</body>
</html>
const listItems = document.querySelectorAll("#data"); selects the table as whole instead of the single table rows. If you specify #data > tr, you'll get the single rows instead and can iterate through them. Try this:
fetch(
"https://gist.githubusercontent.com/SuecoMarcus/a77af69f0e84c3125a5c0cf43a3ac41b/raw/918cd058b7e2286a36e79643c63a5ebca097d7c8/users.json"
).then((response) => {
response.json().then((data) => {
let row = "";
data.forEach((itemData) => {
row += "<tr>";
row += "<td>" + itemData.id + "</td>";
row += "<td>" + itemData.firstname + "</td>";
row += "<td>" + itemData.lastname + "</td>";
row += "<td>" + itemData.age + "</td></tr>";
});
document.querySelector("#data").innerHTML = row;
});
});
document.querySelector("#search-input").addEventListener("input", filterTable);
function filterTable(e) {
const searchInput = document.querySelector("#search-input");
const filter = searchInput.value.toLowerCase();
const listItems = document.querySelectorAll("#data > tr");
listItems.forEach((item) => {
let text = item.textContent;
if (text.toLowerCase().includes(filter.toLowerCase())) {
item.style.display = "";
} else {
item.style.display = "none";
}
});
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
<title>Hack Academy - Proyecto Base</title>
<!-- CSS de Bootstrap -->
<link
href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.0/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-KyZXEAg3QhqLMpG8r+8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We"
crossorigin="anonymous"
/>
<!-- CSS Propio -->
<link rel="stylesheet" href="css/styles.css" />
</head>
<body>
<div class="container mt-5" id="app">
<input
style="width: inherit"
id="search-input"
placeholder="Ingresar texto a buscar...
"
type="search"
/>
<table class="table table-search">
<thead>
<tr>
<th>ID</th>
<th>Nombre</th>
<th>Apellido</th>
<th>Edad</th>
</tr>
</thead>
<tbody id="data"></tbody>
</table>
</div>
<!-- JS de Bootstrap -->
<script
src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.0/dist/js/bootstrap.bundle.min.js"
integrity="sha384-U1DAWAznBHeqEIlVSCgzq+c9gqGAJn5c/t99JyeKa9xxaYpSvHU5awsuZVVFIhvj"
crossorigin="anonymous"
></script>
<!-- JS Propio -->
<script src="js/app.js"></script>
</body>
</html>
I solved your issue by just adding childNodes at the end of querySelector("#data")
So that line should be:
const listItems = document.querySelector("#data").childNodes;
I have a csv file which contains items scraped from a supermarket website. I have now displayed them on html and added a "Add to cart" button. I want the item name and price to be saved on to local storage when the button is pressed.
The idea is to then show these saved data in the basket.
Showing my existing code below.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<!--<link href ="styles.css" type = "text/css" rel="stylesheet">-->
<title>CSV File to HTML Table Using AJAX jQuery</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<!-- Header-->
<div id="header">
<button type="button" class="button">Basket</button>
</div>
<!-- CSV FILE DATA WILL APPEAR HERE-->
<div class="container">
<div class="table-responsive">
<div id="order_list" onload="appendRow()"><p id="tableintro"> Choose your desired supermarket</p>
</div>
</div>
</div>
<!--THIS BUTTON WILL LOAD DATA FROM CSV FILE-->
<div id="sidebar">
<div align="center">
<button type="button" name="load_data" id="load_sainsburys" class="btn btn-info">Sainsburys Colindale</button>
</div>
</div>
//Save item to local storage - DOESNT SEEM TO WORK
<script>
function SaveItem() {
var usrObject = {};
usrObject.product = document.getElementsById("12at").value;
usrObject.price = document.getElementById("34at").value;
//Store User
localStorage[usrObject.product] = JSON.stringify(usrObject);
}
</script>
Below is the code i am using to retrieve data from my CSV file:
<script>
$(document).ready(function(){
$('#load_sainsburys').click(function(){
$.ajax({
url:"sainsburys.csv",
dataType:"text",
success:function(data)
{
var tesco_data = data.split(/\r?\n|\r/);
var table_data = '<table class="table table-bordered table-striped">';
for (var count = 0; count < tesco_data.length; count++)
{
var cell_data = tesco_data[count].split(",");
var name = cell_data[0];
var price = cell_data[1];
if (count === 0)
{
table_data += '<tr><th>' + name + '</th><th>' + price + '</th><th>action</th></tr>';
continue;
}
table_data += '<tr><td id="12at">' + name + '</td><td id="34at">' + price + '</td><td><button type="button onclick="SaveItem()">Add to cart</button></td></tr>';
}
table_data += '</table>';
$('#order_list').html(table_data);
}
});
});
});
</script>
I am trying to pull data from a json file and display it in a table on my web page. The json file is updated dynamically with data about movies from an api. The function that I am using right now is giving a syntax error about needing a name.
I have tried naming the function but so far nothing has worked. I'm new to web development so if it's an obvious answer I'm sorry.
index.html
<!DOCTYPE html>
<html>
<head>
<title>Furby</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<link href="static/layout/styles/layout.css" rel="stylesheet" type="text/css" media="all">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> </script>
<script>
$(function() {
var table = document.getElementById('userdata');
for(var i = table.rows.length - 1; i > 0; i--)
{
table.deleteRow(i);
}
$.getJSON('static/movies.json', function(data) {
$.each(data.movie, function(i, f) {
var url = "https://image.tmdb.org/t/p/w92/" + f.url;
var tblRow = "<tr>" + "<td>" + f.title + "</td>" + "<td>" + "<img id = 'url_img' >" + "</td>" + "</tr>"
$(tblRow).appendTo("#userdata tbody");
document.getElementById('url_img').src = url;
document.getElementById('url_img').id = url;
});
});
});
</script>
</head>
<body id="top">
<div id="pageintro" class="hoc clear">
<!-- ################################################################################################ -->
<div class="flexslider basicslider">
<ul class="slides">
<li>
<article>
<h3 class="heading">Find A Movie</h3>
<p>Search from thousands of online movies!</p>
<footer>
<form class="group" method="post" action="search" onsubmit="function();">
<fieldset>
<legend>Search:</legend>
<input type="text" value="" placeholder="Search Hereā¦" name="search">
<button class="fa fa-sign-in" type="submit" title="Submit"><em>Submit</em></button>
</fieldset>
</form>
</footer>
</article>
<div class="wrapper">
<div class="profile">
<table id= "userdata" border="2">
<thead>
<th>Title</th>
<th>Cover</th>
</thead>
<tbody></tbody>
</table>
</div>
</div>
</li>
</ul>
</div>
<!-- ################################################################################################ -->
</div>
<!-- ################################################################################################ -->
<script src="static/layout/scripts/jquery.min.js"></script>
<script src="static/layout/scripts/jquery.backtotop.js"></script>
<script src="static/layout/scripts/jquery.mobilemenu.js"></script>
<script src="static/layout/scripts/jquery.flexslider-min.js"></script>
</body>
</html>
The code below will update my table with the movie titles and images once but I have to do a hard refresh on the page to get it to update. I assume it's the name error that is preventing it from running this code every time I search a movie.
EDIT: Added more relevant code. Sorry this is my first time posting.
Remove the inline event listener from the form.
<form class="group" method="post" action="search">
Name your function
function performSearch () {
var table = document.getElementById('userdata');
for (var i = table.rows.length - 1; i > 0; i--) {
table.deleteRow(i);
}
$.getJSON('static/movies.json', function(data) {
$.each(data.movie, function(i, f) {
var url = "https://image.tmdb.org/t/p/w92/" + f.url;
var tblRow = "<tr>" + "<td>" + f.title + "</td>" + "<td>" + "<img id = 'url_img' >" + "</td>" + "</tr>"
$(tblRow).appendTo("#userdata tbody");
document.getElementById('url_img').src = url;
document.getElementById('url_img').id = url;
});
});
}
Call your function on page load.
$(function(){
performSearch();
});
And setup the form to perform the search on submit.
$(function(){
performSearch();
$('.group[action="search"]').on('submit', function(e){
e.preventDefault();
performSearch();
});
});
1 ) You have 2 jQuery Lib, that wrong, you need only one also check versions
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> </script>
. . .
<script src="static/layout/scripts/jquery.min.js"></script>
2) your HTML table is not valid : you forget placing forget <tr> .... </tr>
<table>
<thead>
<tr>
<th>Title</th>
<th>Cover</th>
</tr>
</thead>
<tbody id="userdata-tbody"></tbody>
</table>
I also place the id="userdata-tbody" on the <tbody> otherwise you also delete your <thead> row
so place your jQuery lib before the code :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Furby</title>
<link href="static/layout/styles/layout.css" rel="stylesheet" type="text/css" media="all">
<script src="static/layout/scripts/jquery.min.js"></script>
<script src="static/layout/scripts/jquery.backtotop.js"></script>
<script src="static/layout/scripts/jquery.mobilemenu.js"></script>
<script src="static/layout/scripts/jquery.flexslider-min.js"></script>
<script>
$(function () {
var tableUserData = document.getElementById('userdata-tbody');
...
for(var i = tableUserData.rows.length; i--;)
{
tableUserData.deleteRow(i);
}
...
});
</script>
</head>
<body>
...
<table>
<thead>
<tr>
<th>Title</th>
<th>Cover</th>
</tr>
</thead>
<tbody id="userdata-tbody"></tbody>
</table>
...
</body>
</html>
I am trying to display icon after text, like start (*) which will represent Arbitration for medical providers.
<tbody>
#{
int i = 0;
foreach (var item in medProviders)
{
if (item.Arb==true) {
<tr class="sortList" style="cursor:pointer" id="increment-#i" data-id="#item.Id" data-lat="#item.Latitude" data-long="#item.Longitude">
<td>#item.Firstname
br/>
<i class="fa fa-heart"></i>
</td>
<td id="distance-#i"></td>
<td id="duration-#i"></td>
</tr>
i++;
}
}
}
</tbody>
Something like this:
OnClick Script
$(".town").click(function () {
$.getJSON("/NfDocuments/LoadMedicalProviders", { town: $(this).attr('data-town') },
function (data) {
$('#medProviders').empty();
var p = 0;
$.each(data, function () {
$("#medProviders").append("<tr class='sortList' style='cursor:pointer' id='increment-" + p + "' data-id='" + this.Id + "' data-lat='" + this.Lat + "' data-long='" + this.Lon + "'><td>" + this.Title +" <span><i class='fa fa-heart'></i></span> </td><td id='distance-" + p + "'><br/></td><td id='duration-" + p + "'></td></tr>");
p++;
});
});
});
Take A look on the click function
<!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://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<button type="button" class="btn btn-primary mybtn" data-toggle="modal" data-target="#myModal">
Click To add Icon
</button>
<table border="1" class="nytable">
<th>Name</th>
<th>Icon</th>
<tr>
<td>Blah</td>
<td><i class="fa fa-heart"></i></td>
</tr>
</table>
</div>
<script>
$('.mybtn').click(function(){
$('.nytable').append('<tr><td>Blah</td><td><i class="fa fa-heart"></i></td><tr>')
});
</script>
</body>
</html>
I'm working with Data Tables and trying to refresh the incoming data every few seconds without refreshing the page. Initial page load works but after the set delay I get an error "Datatables warning(table id = 'example'): cannot reinitialise data table". Looked at the data table website for help but couldn't find anything specific to my setup. Any feedback appreciated.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Crypto Market Cap</title>
<link rel="icon" type="image/png" href="imgs/favicon.ico" />
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css">
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<link rel="stylesheet" type="text/css" href="css/spritesheet.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<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="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-112760236-1"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-112760236-1');
</script>
<style>
#tableHeader tr td { font-weight:bold }
</style>
</head>
<body>
<img src="imgs/spritesheet.png" width="0" height="0" style="display: none">
<div class="container">
<div class="row" style="text-align:center;margin-bottom:30px">
<h2 class="col-xs-12">
Cryptocurrency Market Capitalizations
</h2>
<h5>$USD</h5>
</div>
<div class="row">
<div class="col-xs-12" style="padding:0">
<table id="dataTable" class="table table-bordered hover" style="margin:0 auto">
<thead id="tableHeader">
<tr>
<td>#</td>
<td>Name</td>
<td>Price</td>
<td>Market Cap</td>
<td>Available Supply</td>
<td>24 HR % Change</td>
</tr>
</thead>
</table>
</div>
</div>
<div class="row">
<div class="col-xs-12" style="text-align:center;margin-top:50px">
<img src="imgs/loading.gif" style="height:120px" id="loading">
</div>
</div>
</div>
<script>
function executeQuery() {
$.ajax({
url: "http://coincap.io/front",
type: "GET",
dataType: "json",
success: function (data) {
var items = [];
var len = data.length;
for (var i = 0; i < len; i++) {
var numFormat = data[i].price.toLocaleString("en");
var numFormat1 = data[i].mktcap.toLocaleString("en");
var numFormat2 = data[i].supply.toLocaleString("en");
var lowerCaseName = data[i].long.toLowerCase();
items.push("<tr><td>" + [i+1] + "</td><td> <span class='sprite sprite-" + lowerCaseName + " small_coin_logo'></span>" + data[i].long + " - " + data[i].short + "</td><td> $" + numFormat + "</td><td> $" + numFormat1 + "</td><td>" + numFormat2 + "</td><td class='marketChange'>" + data[i].cap24hrChange + "% </td></tr>");
}
$("<tbody/>", {
"class": "mainTable",
html: items.join("")
}).insertAfter("#tableHeader");
},
complete: function() {
$("#loading").addClass("hide");
$('#dataTable').DataTable({
"lengthMenu": [ 20, 50, 75, 100 ],
"order": [[ 3, "desc" ]],
language: { search: "" }
});
$('#dataTable_filter input[type="search"]').attr('placeholder', 'Search for coins');
$('#dataTable_filter input[type="search"]').css("padding-left","9px");
}
});
setTimeout(executeQuery, 5000);
}
$(document).ready(function() {
setTimeout(executeQuery, 5000);
});
</script>
</body>
</html>
Create the datatable just once. Move code from complete to document ready. Dont create tbody everytime new get is done. hust append them to the main body.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Crypto Market Cap</title>
<link rel="icon" type="image/png" href="imgs/favicon.ico" />
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css">
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<link rel="stylesheet" type="text/css" href="css/spritesheet.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<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="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-112760236-1"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-112760236-1');
</script>
<style>
#tableHeader tr td { font-weight:bold }
</style>
</head>
<body>
<img src="imgs/spritesheet.png" width="0" height="0" style="display: none">
<div class="container">
<div class="row" style="text-align:center;margin-bottom:30px">
<h2 class="col-xs-12">
Cryptocurrency Market Capitalizations
</h2>
<h5>$USD</h5>
</div>
<div class="row">
<div class="col-xs-12" style="padding:0">
<table id="dataTable" class="table table-bordered hover" style="margin:0 auto">
<thead id="tableHeader">
<tr>
<td>#</td>
<td>Name</td>
<td>Price</td>
<td>Market Cap</td>
<td>Available Supply</td>
<td>24 HR % Change</td>
</tr>
</thead>
<tbody class="mainTable">
</tbody>
</table>
</div>
</div>
<div class="row">
<div class="col-xs-12" style="text-align:center;margin-top:50px">
<img src="imgs/loading.gif" style="height:120px" id="loading">
</div>
</div>
</div>
<script>
function executeQuery() {
$.ajax({
url: "http://coincap.io/front",
type: "GET",
dataType: "json",
success: function (data) {
var items = [];
var len = data.length;
for (var i = 0; i < len; i++) {
var numFormat = data[i].price.toLocaleString("en");
var numFormat1 = data[i].mktcap.toLocaleString("en");
var numFormat2 = data[i].supply.toLocaleString("en");
var lowerCaseName = data[i].long.toLowerCase();
items.push("<tr><td>" + [i+1] + "</td><td> <span class='sprite sprite-" + lowerCaseName + " small_coin_logo'></span>" + data[i].long + " - " + data[i].short + "</td><td> $" + numFormat + "</td><td> $" + numFormat1 + "</td><td>" + numFormat2 + "</td><td class='marketChange'>" + data[i].cap24hrChange + "% </td></tr>");
}
$(".mainTable").append(items.join(""));
},
complete: function() {
}
});
setTimeout(executeQuery, 5000);
}
$(document).ready(function() { $("#loading").addClass("hide");
$('#dataTable').DataTable({
"lengthMenu": [ 20, 50, 75, 100 ],
"order": [[ 3, "desc" ]],
language: { search: "" }
});
$('#dataTable_filter input[type="search"]').attr('placeholder', 'Search for coins');
$('#dataTable_filter input[type="search"]').css("padding-left","9px");
setTimeout(executeQuery, 5000);
});
</script>
</body></html>