Changing JSON file loaded into table by clicking button - javascript

I've been able to get a JSON file to load into a table fine, but I want to have multiple JSON files and change which one is loaded into the table based on which button has been pressed. I thought I could just make it change the variable data, but then the table still stays the same (I'm assuming you have to make it refresh some how?).
Also, on a side note, is it possible to have the prices have a space between them?
test.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Test</title>
<meta name="description" content="Hello World">
<!-- Latest compiled and minified CSS -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="https://rawgit.com/wenzhixin/bootstrap-table/master/dist/bootstrap-table.min.css">
<script src="https://rawgit.com/wenzhixin/bootstrap-table/master/dist/bootstrap-table.min.js"></script>
<script src="data1.json"></script>
<script src="data2.json"></script>
<script>
$(function () {
$('#table').bootstrapTable({
data: data_one
});
$('#data1').on('click', function(event) {
$('#table').bootstrapTable({
data: data_one
});
});
$('#data2').on('click', function(event) {
$('#table').bootstrapTable({
data: data_two
});
});
});
</script>
</head>
<body>
<header>
<div class="jumbotron">
<div class="container">
<h3>Test</h3>
</div>
</div>
</header>
<div class="container">
<div class="row">
<div class="text-center">
<a class="btn btn-large btn-success" id="data1">Data 1</a>
<a class="btn btn-large btn-success" id="data2">Data 2</a>
</div>
</div>
</div>
<div class="container">
<div class="row">
<table id="table" class="table table-bordered" data-search="true" data-show-toggle="true">
<thead>
<tr>
<th data-field="id" data-sortable="true">ID</th>
<th data-field="name" data-sortable="true">Name</th>
<th data-field="prices" data-sortable="true">Price</th>
</tr>
</thead>
</table>
</div>
</div>
<footer>
<div class="container">
<hr>
<p><small>Google didn't help me</small></p>
</div>
</footer>
</body>
</html>
data1.json:
var data_one = [
{
"id": 0,
"name": "test0",
"prices": [
"$0",
"$5"
]
},
{
"id": 1,
"name": "test1",
"prices": [
"$4",
"$1"
]
},
{
"id": 2,
"name": "test2",
"prices": [
"$2",
"$3"
]
},
];
data2.json:
var data_two = [
{
"id": 4,
"name": "test4",
"prices": [
"$1",
"$2"
]
},
{
"id": 5,
"name": "test5",
"prices": [
"$6",
"$5"
]
},
{
"id": 6,
"name": "test6",
"prices": [
"$9",
"$7"
]
},
];

You need to specify the 'load' method when updating the data in the table:
<script>
$(function () {
$('#table').bootstrapTable({ data: data_one });
$('#data1').on('click', function(event) {
$('#table').bootstrapTable('load', { data: data_one });
});
$('#data2').on('click', function(event) {
$('#table').bootstrapTable('load', { data: data_two });
});
});
</script>
For some reason you cannot initially load the data with load method, only update. You can also append data with "append" method and do lot of cool stuff. Check out the documentation here: Bootstrap Table Documentation

1) You don't need all the ready functions, just one (the functions that look like $(function () {..}).
2) Also, you're not calling the plugin on that element again when you click a button - you have to explicitly do that.
3) Finally, you've not added an event listener to your second button - you added a duplicate listener to your first button.
4) You should remove the inline onclick="data1()" and onclick="data2()" from your HTML buttons.
$(function () {
$('#table').bootstrapTable({
data: data_one
});
$('#data1').on('click', function(event) {
$('#table').bootstrapTable({
data: data_one
});
});
$('#data2').on('click', function(event) {
$('#table').bootstrapTable({
data: data_two
});
});
});

You are not integrating data2() function. You can write your code as below.
$(function () {
$('#table').bootstrapTable({
data: data_one
});
});
function data1(){
$('#table').bootstrapTable({
data: data_one
});
}
function data2(){
$('#table').bootstrapTable({
data: data_two
});
}

Related

Jquert Ul Li search using boostrap panel not working

I am using the jquery sim tree plugin to show tree categories. Sim Tree
I have added a search bar to the filter tree data. What I want is to expand the inner ul li elements.
Working Fiddle --> https://jsfiddle.net/dnetk0s9/
The issue is when I search the text second it does not work. (the panel is not expanding).
<!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">
<link rel="stylesheet" href="https://www.jqueryscript.net/demo/Checkable-Hierarchical-Tree/dist/simTree.css">
<link href="https://www.jqueryscript.net/css/jquerysctipttop.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<title>sim-tree: Checkable Hierarchical Tree Demo</title>
<style>
body { min-height: 100vh; background-color: #fafafa;}
.container { margin: 150px auto; max-width: 640px; }
</style>
</head>
<body>
</script>
<div class="container">
<input type="text" name="search" class="form-control" value="" id="demo_2" placeholder="" autofocus style="margin-top:10px;"/>
<br/><br/>
<div class="panel-group" id="accordion">
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" class="ul-laspe" data-parent="#accordion" href="#collapse1">
One
</a>
</h4>
</div>
<div id="collapse1" class="panel-collapse collapse">
<div class="panel-body">
<div class="tree">
<div id="tree"></div>
</div>
</div>
</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" class="ul-laspe" data-parent="#accordion" href="#collapse2">
Two
</a>
</h4>
</div>
<div id="collapse2" class="panel-collapse collapse">
<div class="panel-body">
<div class="tree">
<div id="tree2"></div>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://www.jqueryscript.net/demo/Checkable-Hierarchical-Tree/dist/simTree.js"></script>
<script>
var list = [{
"id": '1',
"pid": '',
"name": "hi foo bar",
},
{
"id": '11',
"pid": '1', // parent ID
"name": "bye tar"
},
{
"id": '12',
"pid": '1',
"name": "welcome rat"
},{
"id": '13',
"pid": '1',
"name": "why this"
},{
"id": '14',
"pid": '1',
"name": "match this"
},
{
"id": '2',
"pid": '',
"name": "raw input"
},
{
"id": '21',
"pid": '2',
"name": ""
}
];
var list2 = [{
"id": '1',
"pid": '',
"name": "X JavaScript",
},
{
"id": '11',
"pid": '1', // parent ID
"name": "X Angular"
},
{
"id": '12',
"pid": '1',
"name": "X React"
},{
"id": '13',
"pid": '1',
"name": "X Vuejs"
},{
"id": '14',
"pid": '1',
"name": "XY jQueryScript.Net"
},
{
"id": '2',
"pid": '',
"name": "X HTML5"
},
{
"id": '21',
"pid": '2',
"name": ""
}
];
var tree = simTree({
el: '#tree',
data: list,
check: true,
linkParent: true,
//check: true,
onClick: function (item) {
console.log(item)
},
onChange: function (item) {
console.log(item)
}
});
var tree = simTree({
el: '#tree2',
data: list2,
check: true,
linkParent: true,
//check: true,
onClick: function (item) {
console.log(item)
},
onChange: function (item) {
console.log(item)
}
});
$('.sim-tree li').each(function(){
$(this).attr('data-search-term', $(this).text().toLowerCase());
});
$('#demo_2').on('change', function() {
//$('.panel-collapse').collapse('hide');
var searchVal = $(this).val().toLowerCase();
var searchTerm = $(this).val().toLowerCase();
if (searchVal != '') {
$('.sim-tree li').each(function() {
var currentLiText = $(this).text().toLowerCase();
showCurrentLi = currentLiText.indexOf(searchVal) !== -1;
if (showCurrentLi) {
$(this).closest('.panel-collapse').collapse('show');
$(this).children("i").click();
$(this).find("ul").addClass("show"); //show ul inside li
} else {
$(this).closest('.panel-collapse').collapse('hide');
$('.panel-collapse').collapse('hide');
$(this).children("i").addClass("layui-icon-r").removeClass("layui-icon-d")
$(this).find("ul").removeClass("show");
}
});
} else {
// $('.panel-collapse').collapse('hide');
$(".sim-tree").find("ul").removeClass("show") //find any ul has show class remove it
$(".sim-tree").children("li").children("i").addClass("layui-icon-r").removeClass("layui-icon-d") //find li children `i` change icon
}
});
</script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</body>
</html>

How can i create an autocomplete with Jquery?

I'm creating a Django site, on a certain template i added an Ajax form and i would like to add an autocomplete feature, in order to make navigation easier.
My main problem is that the data i should search is a JSON array of objects, while most of the solutions i found work with normal arrays.
Here is what i have now:
<script>
$(document).ready(function(){
// Defining the local dataset
$.getJSON('http://127.0.0.1:8000/myapi/', function(data) {
console.log(data)
//Autocomplete
});
});
</script>
<input type="text" id='firstfield' name='input_val'>
This is what the data looks like, it's around 700 records; here are the first three:
"results": [
{
"item": "First",
"id": "1847",
},
{
"item": "Second",
"id": "4442",
},
{
"item": "Third",
"id": "3847",
}]
I need this to be as fast as possible. Is there a JQuery/Ajax native solution for this? Or is there a specific library to do this? Any advice or solution is appreciated, thanks in advance!
You could use the jQuery Typeahead Search plugin. Just set-up your form to use the proper nesting of classes as seen below.
$(() => {
//$.getJSON('http://127.0.0.1:8000/myapi/', function(data) {
let data = {
"results": [
{ "item": "First", "id": "1847" },
{ "item": "Second", "id": "4442" },
{ "item": "Third", "id": "3847" }
]
};
$('#first-field').typeahead({
source: {
data: data.results.map(record => record.item)
},
callback: {
onInit: function($el) {
console.log(`Typeahead initiated on: ${$el.prop('tagName')}#${$el.attr('id')}`);
}
}
});
//})
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/jquery-typeahead/2.11.0/jquery.typeahead.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-typeahead/2.11.0/jquery.typeahead.min.js"></script>
<h1>jQuery Typeahead</h1>
<form>
<div class="typeahead__container">
<div class="typeahead__field">
<div class="typeahead__query">
<input id="first-field" name="first-field" placeholder="Search" autocomplete="off">
</div>
<div class="typeahead__button">
<button type="submit"><i class="typeahead__search-icon"></i></button>
</div>
</div>
</div>
</form>
Try this one:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Autocomplete - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.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>
<script>
$(document).ready(function(){
// Defining the local dataset
$.getJSON('http://127.0.0.1:8000/myapi/', function(data) {
console.log(data)
$( "#tags" ).autocomplete({
source: data
});
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
</div>
</body>
</html>
You can use Jquery autocomplete() function
Here is the link
https://jqueryui.com/autocomplete/
$( "#tags" ).autocomplete({
source: availableTags
});
} );
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure"}

$(...).DataTable is not a function even after including the js before dataTable

I have been trying to integrate a table into my website which pulls data from my database into the table on the website.
I have read all the possible solutions on the internet and couldnt fix the issue yet.
I am putting my code below to have a look.
Please point out where I'm goiing wrong in it and what can i do for it to work.
Otherwise suggest me another option to go for the same function of loading data from the database into the tables inti the HTML site.
The declarations that i have used before the code.
<!--Import jQuery before export.js-->
<script type="text/javascript" src="//code.jquery.com/jquery.js"></script>
<script src="//cdn.datatables.net/1.10.13/js/jquery.dataTables.js"></script>
<!--Data Table-->
<script type="text/javascript" src=" //cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src=" //cdn.datatables.net/buttons/1.2.4/js/dataTables.buttons.min.js"></script>
<!--Export table buttons-->
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jszip/2.5.0/jszip.min.js"></script>
<script type="text/javascript" src="//cdn.rawgit.com/bpampuch/pdfmake/0.1.24/build/pdfmake.min.js" ></script>
<script type="text/javascript" src="//cdn.rawgit.com/bpampuch/pdfmake/0.1.24/build/vfs_fonts.js"></script>
<script type="text/javascript" src="//cdn.datatables.net/buttons/1.2.4/js/buttons.html5.min.js"></script>
<script type="text/javascript" src="//cdn.datatables.net/buttons/1.2.1/js/buttons.print.min.js"></script>
<!--Export table button CSS-->
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/1.2.4/css/buttons.dataTables.min.css">
This is my HTML code.
<div style="width:90%; margin:0 auto;">
<table id="myTable">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
</tr>
</thead>
</table>
</div>
This is my Javascript code.
<script>
$(document).ready(function () {
$('#myTable').DataTable({
"ajax": {
"url": "/api/medical_inventory/",
"type": "GET",
"datatype": "json"
},
"columns" : [
{ "data": "Id", "autoWidth": true },
{ "data": "Name", "autoWidth": true },
]
});
});
</script>
Any help is appreciated.
Thanks in advance.
You probably want to have the ajax call actually return data, and then pass that on to DataTable. As an example:
$.ajax({
url: "/api/medical_inventory/",
type: "GET",
datatype: "json",
success: function(data){
$("#myTable").DataTable({
data: data,
columns : [
{ title: "Id", className: "myClass" },
{ title: "Name", className: "otherClass" },
]
});
}
});

Unable to expand rows after destroy and reload; Cannot read property '_detailsShow' of undefined;

I am using the jQuery DataTable for creating a web page. I have a use case where the page opens with the table already populated. Now, there is a form in the page where he can put some filters and refresh the table. Also, more importantly for each row, I can expand to see more details as explained here.
In my case, as soon as the data is reloaded after the form is submit, the details button which would expand each data row stops working. It gives the following error:
jquery.dataTables.min.js:120 Uncaught TypeError: Cannot read property '_detailsShow' of undefined
I am reloading thee table by first clearing, destroying and then calling the DataTable method. Here's my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.11/css/jquery.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/select/1.1.2/css/select.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="../../../static/css/chosen/bootstrap-chosen.css">
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.1.min.js"></script>
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script type="text/javascript" src="../../../static/js/bootstrap/bootstrap-datetimepicker.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.11/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/select/1.1.2/js/dataTables.select.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.11/js/dataTables.bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(
function ()
{
var dashboard_table_id = "#example";
function destroy_existing_data_table()
{
var existing_table = $(dashboard_table_id).dataTable();
if (existing_table != undefined)
{
existing_table.fnClearTable();
existing_table.fnDestroy();
}
}
function create_dashboard_table()
{
var data_table = $(dashboard_table_id).DataTable({
"data": [{
"dt_RowId": 10,
"column1": "delhivery",
"column2": "CRP12345",
"column3": "1122",
"column4": "One expanded row"
}, {
"dt_RowId": 2,
"column1": "delhivery",
"column2": "CRP12345",
"column3": "1122",
"column4": "Other expanded row"
}],
"columns": [
{"className": "select-checkbox", orderable: false, "data": null, "defaultContent": ""},
{"class": "details-control", "orderable": false, "data": null, "defaultContent": ""},
{"data": "column1"},
{"data": "column2"},
{"data": "column3"}
],
"buttons": {},
"dom": 'lBfrtip',
"select": {
"style": 'multi',
"selector": 'td:first-child'
},
"oLanguage": {"sSearch": ""},
"order": [[2, 'asc']],
"bLengthChange": false,
"pageLength": 25
});
// adding event listener for opening and closing details
$(dashboard_table_id).find('tbody').on('click', 'tr td.details-control',
function ()
{
var tableRow = $(this).closest('tr');
var row = data_table.row(tableRow);
if (row.child.isShown())
{
tableRow.removeClass('details');
row.child.hide();
}
else
{
var rowData = row.data();
tableRow.addClass('details');
row.child("Hello there, this is the expanded view I am referring to....").show();
}
});
}
$("#example-form-submit").click(function (event)
{
event.preventDefault();
destroy_existing_data_table();
create_dashboard_table();
});
create_dashboard_table();
});
</script>
<style>td.details-control {
background: green;
cursor: pointer;
}
tr.details td.details-control {
background: blue;
}</style>
</head>
<body>
<div class="main-content lfloat">
<div class="container" style="width: 100%;">
<label for="example-form-submit" class="col-md-2 control-label"></label>
<div class="col-md-2">
<button type="submit" id="example-form-submit" class="btn btn-primary">Refresh and try to expand</button>
</div>
<div>
<table id="example" class="row-border hover order-column" cellspacing="0" width="100%">
<thead>
<tr>
<th></th>
<th></th>
<th>column1</th>
<th>column2</th>
<th>column3</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
</body>
</html>
Can some one please point out what I am doing wrong. Thanks a ton in advance. This has been bugging me for some time now.
JSFiddle : Credits: #Edis Golubich
it works for me. just remove the latest click event handler by add .off before add the new one.
$(dashboard_table_id).find('tbody').off('click', 'tr td.details-control');
$(dashboard_table_id).find('tbody').on('click', 'tr td.details-control',function(){...});
The issue is that the data_table object is not getting 'updated' when using jQuery.on() via delegated event handling.
Try this: https://jsfiddle.net/f5mdcrup/4/
What I did was declare data_table outside of the function. The scope will be different in this case.
Following code works for me
$(dashboard_table_id).find('tbody').off('click', 'tr td.details-control');
$(dashboard_table_id).find('tbody').on('click', 'tr td.details-control',function(){
//Action To perform
});

DataTables cannot add row

I'm trying to add data to a table dynamically through JavaScript, and it returns this:
Uncaught TypeError: Cannot read property 'add' of undefined.
EDIT: The code works perfectly without the row.add line.
Relevant code:
<html>
<head>
<link rel="stylesheet" type="text/css" href="./css/jquery.dataTables.min.css">
<script type="text/javascript" src="./lib/jquery.min.js"></script>
<script type="text/javascript" src="./lib/jquery.dataTables.min.js"></script>
<script>
var dataSet = [
['1.1','2.1'],
['1.2','2.2'],
];
$(document).ready(function() {
$('#demo').html( '<table cellpadding="0" cellspacing="0" border="0" class="display" id="example"></table>' );
t = $('#example').dataTable(
{
data: dataSet,
columns: [
{ "title": "Col 1" },
{ "title": "Col 2" },
],
});
t.row.add(['1.3', '2.3']) // <-- Fails
});
</script>
</head>
<body>
<div id="demo" style="width:500px"> </div>
</body>
</html>
You are very close. Here is the change I have done to your code:
a. While initializing DataTable, used capital D.
b. Used .draw(); while adding row.
var dataSet = [
['1.1','2.1'],
['1.2','2.2']
];
$(document).ready(function() {
$('#demo').html('<table cellpadding="0" cellspacing="0" border="0" class="display" id="example"></table>');
var t = $('#example').DataTable({
data: dataSet,
columns: [
{ "title": "Col 1" },
{ "title": "Col 2" }
]
});
t.row.add(['1.3', '2.3']).draw();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link href="//cdn.datatables.net/1.10.7/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="//cdn.datatables.net/1.10.7/js/jquery.dataTables.min.js"></script>
<div id="demo" style="width:500px"></div>

Categories