Bootstrap table pagination and searching is not working - javascript

I am new to bootstrap and working in D3.js, crossfilter.js to generate the table contents. I like to get the dataTable as in the following URL with some pagination and searching with in the datatable using bootstrap.
In that example the table is statically defined with id and class. I am able to run the html page with the desired output as in the example page source code.
But in my case I am generating a table from function and not able to get the pagination and searchBox on top of the table. I added all the supported files such as js and css files.
Here is my code and I just reduced the code to avoid more spaces in this portal. May I know where I am doing mistake.
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=us-ascii">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>DataTables example - Bootstrap</title>
<link rel="shortcut icon" type="image/png" href="/media/images/favicon.png">
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/plug-ins/380cb78f450/integration/bootstrap/3/dataTables.bootstrap.css" />
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="https://cdn.datatables.net/1.10.3/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/plug-ins/380cb78f450/integration/bootstrap/3/dataTables.bootstrap.js"></script>
</head>
<body>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/d3/2.10.0/d3.v2.min.js"></script>
<script type='text/javascript' src="crossfilter.js"></script>
<div id="Default" class="default"></div>
<script>
$(document).ready(function () {
$('#example').dataTable();
$('#Default').show();
});
d3.json("myJson.json", function (desing) {
var data = desing;
var ndx = crossfilter(data);
var state1 = ndx.dimension(function (d) {return d.region;});
var dist1 = ndx.dimension(function (d) { return d.cluster;});
var taluk1 = ndx.dimension(function (d) { return d.center;});
var village1 = ndx.dimension(function (d) { return d.loan_type_id;});
cfds = ndx.dimension(function (d) {return d.region; });
$("#Default").html(totable(cfds.top(Infinity)));
cfds.filterAll();
});
function totable(json) {
var html = "";
html += "<thead>"
html += "<tr>"
html += "<th>REGION</th>"
html += "<th>CLUSTER</th>"
html += "<th>CENTER</th>"
html += "<th>GLP MONTH</th>"
html += "<th>LOAN AMT DISBURSED</th>"
html += "<th>NEW MEMBERS</th>"
html += "<th>DEMAND</th>"
html += "<th>PRINCIPAL</th>"
html += "<th>INTEREST</th>"
html += "<th>WRITTEN OFF</th>"
html += "<th>HM-PROCESSED</th>"
html += "<th>HM-ELIGIBLE</th>"
html += "<th>Eligible %</th>"
html += "<th>LOAN TYPE</th>"
html += "</tr>"
html += "</thead>"
json.forEach(function (row) {
html += "<tr role='row'>";
for (key in row) {
html += "<td>" + row[key] + "</td>";
};
html += "</tr>";
});
return "<table id='example' class='table table-striped table-bordered' cellspacing='0' width='100%' role='grid' aria-describedby='example_info'>" + html + "</table>";
}
</script>
</body>
</html>

It is working after I put the supported js files has been defined upon the end of the body tag.Also I initiate the dataTable under d3 function. All goes well now.
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="http://cdn.datatables.net/1.10.3/js/jquery.dataTables.min.js"></script>
</body>
</html>
Hope its useful for someone..

Related

Populate form after mySQL query with javascript

I'm trying to do this thing:
I have a html input textbox, some php code that makes a query on my database and return a JSON element, and in the end some javascript that I cannot figure to work the right way.
I simply want to do a live search while user is typing, than select one of the record found from the live search and populate a form with data of this record.
Probably there is a very simple solution, but I'm a newbie.
This is my html and Javascript code:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>InChiaro Ticket Admin</title>
<meta name="description" content="The HTML5 Herald" />
<meta name="author" content="SitePoint" />
<link href="../assets/bootstrap/css/bootstrap.min.css" rel="stylesheet" />
<link href="../assets/bootstrap/css/bootstrap-responsive.min.css" rel="stylesheet" />
<link href="../assets/bootstrap/css/bootstrap-fileupload.css" rel="stylesheet" />
<link href="../assets/font-awesome/css/font-awesome.css" rel="stylesheet" />
<link href="css/style.css" rel="stylesheet" />
<link href="css/style-responsive.css" rel="stylesheet" />
<link href="css/style-default.css" rel="stylesheet" id="style_color" />
<link href="../assets/fullcalendar/fullcalendar/bootstrap-fullcalendar.css" rel="stylesheet" />
<link href="../assets/jquery-easy-pie-chart/jquery.easy-pie-chart.css" rel="stylesheet" type="text/css" media="screen" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
</head>
<body>
<div id="main-content">
<div class="wrapper-principale">
<div class="input-append search-input-area">
<input type="text" class="search-filter" id="searchcodiceCliente" name="codiceCliente" placeholder="Cerca un cliente..." /> <!-- text AREA CODICE CLIENTE-->
<button class="btn" type="button"><i class="icon-search"></i> </button>
</div>
<div id="result" style="display:none">
<table id="tablesearch"></table>
</div>
<form>
<input type="text" id="CodiceCliente" />
<input type="text" id="denominazione" />
</form>
</div>
</div>
<script type="text/javascript">
$(function () {
// We add the event on the class, which both inputs have
$(".search-filter").keyup(function () {
// Now we get the values from both inputs, using their ID's
var codiceCliente = $("#searchcodiceCliente").val();
//var fname = $("#searchfname").val();
// Add both to the dataString (and URI encode the strings)
var requestCodCliente = "get_codiceCliente_json"
var json;
// Check that at least one has any content
if (codiceCliente != '')
$.ajax({
type: "POST",
url: "ajax_requests.php",
data: {
request: requestCodCliente,
searchCliente: codiceCliente
},
success: function (result) {
var x = document.getElementById("result");
x.style.display = "inline";
document.getElementById("tablesearch").innerHTML = '';
var th = "<tr><th></th><th>Codice Cliente</th><th>Denominazione</th><th>Indirizzo</th><th>Città</th><th>CAP</th><th>Numero Telefono</th></tr>";
document.getElementById("tablesearch").innerHTML += th;
function populateForm() {
document.getElementById("CodiceCliente").value = result[index].codiceCliente;
}
for (var index = 0; index < result.length; ++index) {
var t = "";
var tr = "<tr>";
tr += "<td><button id='select' class='btn'type='button' onclick='populateForm()'><i class='icon-search'></i></button></td>";
tr += "<td>"+result[index].codiceCliente+"</td>";
tr += "<td>"+result[index].denominazioneCliente+"</td>";
tr += "<td>"+result[index].indirizzo+"</td>";
tr += "<td>"+result[index].citta+"</td>";
tr += "<td>"+result[index].CAP+"</td>";
tr += "<td>"+result[index].numeroTelefono+"</td>";
tr += "</tr>";
t += tr;
document.getElementById("tablesearch").innerHTML += t;
}
}
});
});
});
</script>
</body>
</html>
And this is some sample output that I hope explains what I mean:
Codice cliente denominazione
c00106 Paolo re
c00116 viglino arturo
c00126 sellaro giuseppe
c00146 accusani fabio
c00161 franconi srl
Thank You
The aspect you are struggling with most is the attachment of populateForm as a click handler. As it stands, onclick='populateForm() won't work because populateForm would need to be a global member, and it's good practice not to pollute the global namespace.
To overcome this, click handling can be delegated to ancestor element of the buttons'; the <table> element is the most obvious choice. Fortunately, jQuery has a very convenient syntax for event delegation.
In addition, there is an issue you are probably not aware of; namely that multiple quick-fire AJAX requests will not necessarily respond in the expected order. On the assumption that order matters, a simple mechanism is available to ensure that table entries are in the expected order. All you need to do is :
when each AJAX request is made, synchronously append a <tbody> element.
keep a reference to each appended <tbody> element (in a closure).
when each AJAX responses is received, append rows to the appropriate <tbody> element.
Your code should be something like this :
$(function () {
// Delegate handling of button.btn clicks to the containing table element.
// This avoids having to attach the same click handler repeatedly to buttons in dynamically generated lines.
$("#tablesearch").on('click', 'button.btn', function() {
$("#CodiceCliente").val($(this).closest('td').next('td').text());
});
$(".search-filter").keyup(function() {
var codiceCliente = $(this).val();
if (codiceCliente != '') {
var $tbody = $('<tbody/>').appendTo("#tablesearch"); // Synchronously append a <tbody> to receive two asynchrously generated <tr>s (see below).
$.ajax({
'type': 'POST',
'url': 'ajax_requests.php',
'data': {
'request': 'get_codiceCliente_json',
'searchCliente': codiceCliente
},
}).then(function (result) {
$("#result").css('display', "inline");
$("<tr><th></th><th>Codice Cliente</th><th>Denominazione</th><th>Indirizzo</th><th>Città</th><th>CAP</th><th>Numero Telefono</th></tr>").appendTo($tbody); // append to the correct <tbody> for this response
for (var i = 0; i < result.length; ++i) {
$("<tr><td><button class='btn'><i class='icon-search'></i></button></td><td>" +
result[i].codiceCliente + "</td><td>" +
result[i].denominazioneCliente + "</td><td>" +
result[i].indirizzo + "</td><td>" +
result[i].citta + "</td><td>" +
result[i].CAP + "</td><td>" +
result[i].numeroTelefono + "</td></tr>").appendTo($tbody); // append to the correct <tbody> for this response
}
}, function() {
$tbody.remove(); // ajax failed so no point keeping the <tbody> element (unless you want to display an error message in the table)
});
}
});
});

How to use Templates on javascript?

I Have A function that add html to a div.
var user = $("#ddlUser").val();
var role = $("#ddlUserRole").val();
var html = '<div class="calendaruser">';
html += '<span>' + user + '</span> <button type="button" class="btn btn-default btn-xs">הסר משתמש</button>';
html += '<div>' + role + '</div>';
html += '</div>';
$("#divCalendarUsers").append(html);
i'm looking for a better way to use the template.
You can use the template literal:
A little sample:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Array2Table</title>
</head>
<body>
<div id="tableContent"></div>
<script>
var country = ["Country1", "Country2", "Country3"];
var capital = ["City1", "City2" , "City3"];
const tmpl = (country,capital) => `
<table><thead>
<tr><th>Country<th>Capital<tbody>
${country.map( (cell, index) => `
<tr><td>${cell}<td>${capital[index]}</tr>
`).join('')}
</table>`;
tableContent.innerHTML=tmpl(country, capital);
</script>
</body>
</html>
To use template in javascript, try handlebarsjs.
I male a function that creates the element taking two arguments (role and user).The return of this function you can bind it in every DOM element you want
function createTemplate(user,role){
var divCalendar=$('<div class="calendaruser"></div>');
var buttonElm=$('<button type="button" class="btn btn-default btn-xs">הסר משתמש</button>');
var spanElm=$('<span>'+user+'</span>');
var divELm=$('<div>'+role+'</div>');
divCalendar.append(buttonElm).append(spanElm).append(divELm);
return divCalendar;
}
//Example below:
$('body').append(createTemplate('user_value', 'role_value'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

JavaScript HTML Rendering Out of Sync -- Spring MVC Project

I have a dashboard site in the works, and it makes use of SpringMVC, FusionCharts, and Bootstrap (to give an architectural overview). When I freshly start up the Tomcat server, the very first time I'm served the index page, a panel of buttons will not render properly. I get the correct number of white circles with question marks as made in the first of 3 javascript functions. If I refresh the page, the intended red and green results immediately come up, generated by the second script function.
As a preamble, the panel with buttons on it is correctly generated with the right count, correct names, correct HREFs and all else. The colors just do not change until the page is refreshed. Back when this project was first constructed, the data was being gathered via http request server-side. It was comparably slow to what is occurring now: loading the data from a file server-side and sending it through in the same format. The old way always produced the correct colors and icons after a 10-second wait. Now, the buttons just remain blank white until I refresh the page, and then I get the right results.
I believe this is just the result of two Javascript functions stepping on each other, even though I know JavaScript is single-threaded. If not, I'm stumped and lost.
Index.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Free Bootstrap Admin Template : Dream</title>
<!-- Bootstrap Styles-->
<link href="css/bootstrap.min.css" rel="stylesheet" />
<!-- FontAwesome Styles-->
<link href="css/font-awesome.css" rel="stylesheet" />
<!-- Morris Chart Styles-->
<link href="js/morris/morris-0.4.3.min.css" rel="stylesheet" />
<!-- Custom Styles-->
<link href="css/custom-styles.css" rel="stylesheet" />
<!-- Google Fonts-->
<link href='https://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css' />
<script type="text/javascript" src="js/fusioncharts/core/fusioncharts.js"></script>
<script type="text/javascript" src="js/fusioncharts/themes/fusioncharts.theme.fint.js"></script>
</head>
<body>
...
<!-- this is where the button panel is correctly created on every load
but only correctly modified on the 2nd load and later -->
<div class="row"> <div id="AppStatusTable"></div> </div>
...
<script src="js/jquery-1.10.2.js"></script>
<!-- Bootstrap Js -->
<script src="js/bootstrap.min.js"></script>
<!-- Metis Menu Js -->
<script src="js/jquery.metisMenu.js"></script>
<!-- Morris Chart Js -->
<script src="js/morris/raphael-2.1.0.min.js"></script>
<script src="js/morris/morris.js"></script>
<!-- Custom Js -->
<!--
<script src="js/custom-scripts.js"></script> -->
<script>
$(document).ready(function(){
$.get("/buttoninfo", function(data, status) {
tableMaker(data, "AppStatusTable");
});
$.get("/appstatus", function(data, status) {
appStatus(data);
});
$.get("/stackstatus", function(data, status) {
stackUpdater(data);
});
});
</script>
</body>
These last 3 functions fill out the html of a panel to contain a dynamic number of buttons, modify the inner html of those buttons, and then update other panels. The third currently takes a while and always produces correct results. I don't suspect it is the issue.
dashboard.js
function templateLoader(appTag) {
//$.get('/app/' + appTag);
window.location = "/app/" + appTag;
}
function appStatus(data){
for(var i = 0; i < data.length; ++i) {
if(data[i][1] == "up"){
$("#" + data[i][0] + "-appcheck").removeClass("btn-default");
$("#" + data[i][0] + "-appcheck").addClass("btn-success");
$("#" + data[i][0] + "-appcheck-icon").removeClass("fa-exclamation-circle");
$("#" + data[i][0] + "-appcheck-icon").addClass("fa-check");
} else if(data[i][1] == "down"){
$("#" + data[i][0] + "-appcheck").removeClass("btn-default");
$("#" + data[i][0] + "-appcheck").addClass("btn-danger");
$("#" + data[i][0] + "-appcheck-icon").removeClass("fa-exclamation-circle");
$("#" + data[i][0] + "-appcheck-icon").addClass("fa-close");
}
}
}
function tableMaker(data, tableID) {
/* vars used below as the skeleton of the injected buttons*/
var i = 0, j = 0, colLimit = 12;
for(; i < data.length;){
for (var j = 0; j < colLimit && i < data.length; ++j, ++i) {
mytable += colStart + data[i][2] + titleEnd + '\n' + buttonStart + data[i][2] + buttonMiddle1 +
data[i][2] + buttonMiddle2 + data[i][2] + buttonMiddle3 + '><i id="' + data[i][2] +
buttonEnd + colEnd;
}
}
panel += mytable + panelEnd;
document.getElementById(tableID).innerHTML = panel;
}
function stackUpdater(data){
for(var i = 0; i < data.length; ++i){
var curStack = data[i][0];
for(var j = 1; j < data[i].length; j++) {
if(data[i][j] == null) {
break;
} else {
$("#" + curStack + j).removeClass("progress-bar-info");
if(data[i][j] == "up") {
$("#" + curStack + j).addClass("progress-bar-success");
} else {
$("#" + curStack + j).addClass("progress-bar-danger");
}
}
}
}
}
I understand browsers cache the results of javascript functions, but the third function is run on every refresh, so why wouldn't the first two be? And thus, why would the results of the second function only appear after refreshing?
What needs to be changed to make sure the buttons modify correctly the FIRST time this page is loaded?
UPDATE 1
After inserting alerts between the function calls, the rendering works on the first try, so what's the correct way to ensure synchronization without this?
Bottom of Index.html:
$(document).ready(function(){
$.get("/buttoninfo", function(data, status) {
tableMaker(data, "AppStatusTable");
});
alert("Button table made!");
$.get("/appstatus", function(data, status) {
appStatus(data);
});
alert("Button Data Updated!");
$.get("/stackstatus", function(data, status) {
stackUpdater(data);
});
alert("Stack Data Updated!");
});
</script>
Instead of using $.get try using $.ajax with cache set to false. If $.get is absolute necessary try adding a timestamp with each request. You may refer to How to set cache: false in jQuery.get call.
Hope that help.

How to keep page design when I print it new tab Jquery?

I use this function to make print
function printContent(el,tble,img) {
var printcontent = document.getElementById(el).innerHTML
+" <div class='row'><span class='glyphicon glyphicon-tasks'></span><b></b></div>"
+ document.getElementById(tble).innerHTML
+ document.getElementById(img).innerHTML;
var w = window.open();
$(w.document.body).html(printcontent);
w.print();
}
this works fine for me but the problem is it didn't contain the same page design and the print page has no design
please help
You should use a link in the head of your page:
<link rel="stylesheet" type="text/css" media="print" href="style.css">
Note the media attribute.
Edit:
var bodyContent = document.getElementById(el).innerHTML
+" <div class='row'><span class='glyphicon glyphicon-tasks'></span><b></b></div>"
+ document.getElementById(tble).innerHTML
+ document.getElementById(img).innerHTML;
var windowHTML = '<html><head><title>Print page</title><link rel="stylesheet" type="text/css" media="print" href="style.css"></head><body>' + bodyContent + '</body>';
var w = window.open();
w.document.write(windowHTML);
w.print();

Displaying multiple user outputs using JavaScript

I am trying to display multiple user outputs, so that when something is entered in the text field, it is captured and displayed in the div.
At the moment it keeps overwriting with the new result rather than adding to what is already displayed.
Can anyone help with this?
HTML:
<!DOCTYPE HTML>
<html lang="en">
<!-- more meta data needs to go in here -->
<head>
<script type="text/javascript" src="main_app_javascript.js"></script>
<link rel="stylesheet" type="text/css" href="">
<meta charset="UTF-8">
<title>List Check</title>
</head>
<body>
<input type="text" id="enter_box">
<button onclick="output_function()"> Add To List </button>
<div id="list_output"></div>
</body>
JavaScript:
function output_function() {
var user_input = document.getElementById("enter_box").value;
document.getElementById("list_output").innerHTML = user_input;
}
Do
document.getElementById("list_output").innerHTML += user_input + '<br />';
instead.
This will concatenate your value and add a line break at the end of the text, to create a "list". Notice the =+ and + '<br /> differences.
You could also try this
function output_function() {
'use strict';
var user_input = document.getElementById("enter_box").value;
var list_output = document.getElementById("list_output");
if( list_output.innerHTML === '' ) {
list_output.innerHTML = '<p>' + user_input + '</p>';
} else {
list_output.innerHTML += '<p>' + user_input + '</p>';
}
}

Categories