Pass JSON result from AJAX to HTML - javascript

I am querying a fuseki server using AJAX and the result that I am getting is a JSON object.
I would like to use pagination to go through the result with a limit of records per page. I have tried to send the JSON object to a div in the html file but it is not working. Is there a workaround this? Here is my code:
function myCallBack2(data) {
var all_results = '';
for (var i = 0; i < data.results.bindings.length; i++) {
var bc = '';
if (i % 2 == 0) {
bc = '#b8cddb';
} else {
bc = '#f2f5f7';
}
all_results += '<div class="all_results" style="background-color:' + bc + '">';
for (var j = 0; j < data.head.vars.length; j++) {
var text = data.results.bindings[i][data.head.vars[j]].value;
var type = data.results.bindings[i][data.head.vars[j]].type;
all_results += '<div class="result_row">';
if (type == ('literal')) {
all_results += '<p> ' + data.head.vars[j] + ": " + text + '</p>';
} else {
all_results += '<a href=' + text + " title=" + data.head.vars[j] + '>' + text + '</a>';
}
all_results += '</div>';
}
all_results += '</div>';
}
$('#result').html(all_results);
}
function doSparql() {
var myEndPoint = "http://localhost:3030/Test/query";
name = document.getElementById("search").value;
var requiredName = "?Author foaf:firstName \"" + name + "\".}";
myQuery = ["PREFIX dcterms: <http://purl.org/dc/terms/>",
"PREFIX foaf: <http://xmlns.com/foaf/0.1/>",
"PREFIX locah: <http://data.archiveshub.ac.uk/def/>",
"SELECT ?Register ?Id ?Date ?Type",
"WHERE{",
"?Register dcterms:creator ?Author.",
"?Register dcterms:identifier ?Id.",
"?Register dcterms:type ?Type.",
"?Register locah:dateCreatedAccumulatedString ?Date.",
requiredName
].join(" ");
console.log('myQuery: ' + myQuery);
window.alert(myQuery);
$.ajax({
dataType: "jsonp",
url: myEndPoint,
data: {
"query": myQuery,
"output": "json"
},
success: myCallBack2,
error: myError
});
console.log('After .ajax');
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="//raw.github.com/botmonster/jquery-bootpag/master/lib/jquery.bootpag.min.js"></script>
<div id="page-selection1" "></div>
<div id="result " class="result "></div>
<div id="page-selection2 "></div>
<script>
$('#page-selection1,#page-selection2').bootpag({
total: 50,
page: 1,
maxVisible: 5,
leaps: true,
firstLastUse: true,
first: 'First',
last: 'Last',
wrapClass: 'pagination',
activeClass: 'active',
disabledClass: 'disabled',
nextClass: 'next',
prevClass: 'prev',
lastClass: 'last',
firstClass: 'first'
}).on("page ", function(event, num) {
$("#result ").html("Page " + num);
});
</script>
I am expecting to show part of the results instead Page 1, Page 2... in #result according to a limit per page.

Related

Push a list into array in JavaScript

I have a list of Data I get from dynamic inputs like this ones
FirstNames : Person1 FN, Person2 FN, Person3 FN, ...
LastNames : Person1 LN, Person2 LN, Person3 LN, ...
The list is dynamic and I'm Getting the values by input Name like this
var FirstNames = $("input[name='FirstName']").map(function(){return $(this).val();}).get();
I want to pass these and many others to my C# backend as an array like This
details:[
0: {FirstName: 'Person1 FN', LastName: 'Person1 LN'}
1: {FirstName: 'Person2 FN', LastName: 'Person2 LN'}
....................................................
N{FirstName: 'PersonN FN', LastName: 'PersonN LN'}
]
I tried many different approaches like split() & Push() as below
let FNs = [];
let FN = FirstNames.toString().split(',');
console.log("Splitted First Names : "+TFNs);
$.each(TFNs, function(){
FNs.push({FirstName:$(this)}.toString());
});
console.log("First Names[] : "+FNs);
Edit : Added Form markup(dynamic) & JS Save() Function
Here is the form (dynamically generated)
function GenerateFrms(Id) {
//alert('Function Scripts');
$("#FrmContainer").empty();
var html = "";
$.ajax({
type: "POST",
url: "WebService.asmx/GenerateForms",
data: "{'Id':'" + Id + "'}",
contentType: "application/json",
dataType: "json",
success: function (data) {
console.log(Object.values(data))
try {
for (var i = 0; i <= data.d.length; i++) {
if (data.d[i].Persons != "0") {
html += " <div class='theme-box-shadow theme-border-radius bg-light mb-3'> ";
html += " <div class='row border-bottom py-2 m-auto'> ";
html += " <div class='col-8'>";
html += " <div class='fw-bold font-medium'> Details </div> ";
html += " </div> ";
html += "<div class='col-4 text-end align-self-center'> ";
html += " <a class='font-small' data-bs-toggle='collapse' href='#collapseFrm' role='button' aria-expanded='false' aria-controls='collapseFrm'><i class='bi bi-chevron-down ps-1'></i></a>";
html += " </div>";
html += " </div>";
html += " <div class='' id='collapseFrm'> ";
html += " <div class='row'> ";
html += " <div class='col-sm-12'> ";
html += " <div class='px-3 FrmDetails' id='FrmDetails'> ";
for(var j=1; j<=data.d[i].Persons; j++)
{
html += " <legend class='fw-bold' style='border-bottom:2px solid blue;'> Persons " + j + " Details</legend> ";
html += " <ul class='row py-3'> ";
html += " <li class='col-12 col-md-12 pb-3'> ";
html += " <div class='row'> ";
html += " <div class='col-12 col-sm-6 col-md-3 mb-3 mb-md-0'> ";
html += " <label for='inlineFormSelectTitle3'> selected Title </label> ";
html += " <select class='form-select Title' name='Title' id='Title" + j + "' > ";
html += " <option selected>Title</option> ";
html += " <option value='Mr'>Mr.</option> ";
html += " <option value='Mrs'>Mrs.</option> ";
html += " <option value='Ms'>Ms.</option> ";
html += " </select> ";
html += " </div> ";
html += " <div class='col-12 col-sm-6 col-md-3 mb-3 mb-md-0'> ";
html += " <label for='inlineFormSelectTitle3'> First Name </label> ";
html += " <input type='text' class='form-control FirstName' name='FirstName' id=' FirstName" + j + "' placeholder='First Name'> ";
html += " </div> ";
html += " <div class='col-12 col-sm-6 col-md-3 mb-3 mb-md-0'> ";
html += " <label for='inlineFormSelectTitle3'> Last Name </label> ";
html += " <input type='text' class='form-control LastName' name='LastName' id=' LastName" + j + "' placeholder=' Last Name'> ";
html += " </div> ";
html += " <div class='col-12 col-sm-6 col-md-3 mb-3 mb-md-0'> ";
html += " <label for='inlineFormSelectTitle3'> Date of Birth </label> ";
html += " <label class='visually-hidden' for='DateofBirth'> Date of Birth</label> ";
html += " <input type='date' class='form-control DOB' name='DOB' id='DOB" + j + "'> ";
html += " </div> ";
html += " </div> ";
html += " </li> ";
html += " </li> ";
html += " </ul> ";
}
html += " </div> ";
html += " </div> ";
html += " </div> ";
html += " </div> ";
html += " </div> ";
}
$("#FrmContainer").append(html)
}
//
} catch (e) {
console.log(e);
}
},
error: function (xhr, status, e) { alert(xhr.responseText); }
});
}
The Script function with Sample static data I'm working with now(I want get them dynamically from the above form)
function Save() {
$('#create').prop('disabled', true);
//Reading Values from the respective inputs/select
var Titles = $("select[name='Title']").map(function(){return "Title:"+$(this).val();}).get();
var FNames = $("input[name='FirstName']").map(function(){return $(this).val();}).get();
var LNames = $("input[name='LastName']").map(function(){return $(this).val();}).get();
var DOBs = $("input[name='DOB']").map(function(){return "DOB:"+$(this).val();}).get();
//here I want to put them in array like `details[]` array below
setTimeout(function () {
let details=[];
details.push({
Title:"Mr.",
FirstName:"Person1 FN",
LastName:"Person1 LN",
DOB:"1990-05-20"
});
details.push({
Title:"Mrs.",
FirstName:"Person2 FN",
LastName:"Person2 LN",
DOB:"2001-06-18"
})
console.log(details);
var DataCarrier = {
Id: Id, //From Query string
PersonsDetails:details
};
$.ajax({
type: "POST",
url: "WebService.asmx/SavePersons",
data: JSON.stringify(DataCarrier),
contentType: "application/json",
dataType: "json",
success: function (data) {
try {
if (data != null) {
setTimeout(function () { window.location = "destinationPage.aspx?Id=" + Id; }, 500);
}
} catch (e) {
console.log(e);
}
},
error: function (xhr, status, e) { alert(xhr.responseText); }
});
}, 5000);
}
And the button
<input id="btnSave" class="btn btn-effect btn-book px-5" type="button" value="Continue" onclick="Save();" />
But I'm getting them as
[object Object],[object Object],[object Object],[object Object],[object Object]
I also tried .toString() but nothing changes, And console.log("FNs : "+json.stringify(FNs)); is throwing error.
How can I process these data as mentioned above before passing them to the backend? What I'm doing wrong? Is there a better way to do what I want achieve?
First step is to read the values from the inputs or select
//Reading Values from the respective inputs/select
var Titles = $("select[name='Title']").map(function() { return $(this).val(); }).get();
var FNames = $("input[name='FirstName']").map(function() { return $(this).val(); }).get();
var LNames = $("input[name='LastName']").map(function() { return $(this).val(); }).get();
var DOB = $("input[name='DOB']").map(function() { return $(this).val(); }).get();
Then split the values into array
//splitting the values into arrays
let TL = Titles.toString().split(',');
let FN = FNames.toString().split(',');
let LN = LNames.toString().split(',');
let BD = DOB.toString().split(',');
After that you can push them into the details[] array using for loop like this
let details = [];
for (var i = 0; i < FNames.length; i++) {
details.push({
Title: TL[i],
FirstName: FN[i],
LastName: LN[i],
DOB: BD[i],
TravllerType: TT[i]
});
}
console.log(JSON.stringify(details));
Note: if you console.log(details); you will find out that its object:Object stuff, to get around this, we stringify it.
finally incorprate all that into your SavePersons() function
function SavePersons() {
$('#create').prop('disabled', true);
//Reading Values from the respective inputs/select
var Titles = $("select[name='Title']").map(function () { return $(this).val(); }).get();
var FNames = $("input[name='FirstName']").map(function () { return $(this).val(); }).get();
var LNames = $("input[name='LastName']").map(function () { return $(this).val(); }).get();
var TravllerTypes = $("input[name='TravllerType']").map(function () { return $(this).val(); }).get();
var DOB = $("input[name='DOB']").map(function () { return $(this).val(); }).get();
//splitting the values into arrays
let TL = Titles.toString().split(',');
let FN = FNames.toString().split(',');
let LN = LNames.toString().split(',');
let TT = TravllerTypes.toString().split(',');
let BD = DOB.toString().split(',');
setTimeout(function () {
let details = [];
for (var i = 0; i < FNames.length; i++) {
details.push({
Title: TL[i],
FirstName: FN[i],
LastName: LN[i],
DOB: BD[i],
TravllerType: TT[i]
});
}
console.log(details);
var DataCarrier = {
Id: Id,
TravelersDetailsTT: details
};
$.ajax({
type: "POST",
url: "WebService.asmx/SavePersons",
data: JSON.stringify(DataCarrier),
contentType: "application/json",
dataType: "json",
success: function (data) {
try {
if (data != null) {
setTimeout(function () { window.location = "destinationPage.aspx?Id=" + Id; }, 5000);
}
} catch (e) {
console.log(e);
}
},
error: function (xhr, status, e) { alert(xhr.responseText); }
});
}, 5000);
}
it may not be the best answer but it works and I tested it. any improves are welcome. in the mean time I hope it helps.
I think the index of firstName and lastName in your array is identical so
var FirstNames = $("input[name='FirstName']")
.map(function(){return $(this).val();}).get();
var LastNames = $("input[name='LastName']")
.map(function(){return $(this).val();}).get();
var FN = FirstNames.map((FN,index) => {
return {{FirstName: FN, LastName: LastNames[index]}
})
It should be something like what you want

Ajax search with pagination.js and/or PHP

I want to do a search that can be triggered by given a specific URL (I tried with ajax and javascript here but im happy with a php variant also). I have 2 requirement phases (both should be displayed with pagination.js):
When I access eg.: https://<.myDomain.>/search/234x15 to put
the value inside the input and the filter automatically or make the
search over the whole database.
When I would go to eg.: https://<.myDomain.>/search I want to make POST search over the whole database.
My general problem is that I cannot include MySQL or other databases, I am limited to either JSON or objects/arrays (JS/php).
With my current solution processing 900 items using a big JSON file gets me a response after 5-8 seconds which is too long. And I will need to fill in with at least 3500 items.
Here is the solution I made:
<script>
var currentKeywords = $(location).attr('pathname');
var currentKeywordsFiltered = currentKeywords.replaceAll('+',' ');
const toBeSearched = currentKeywordsFiltered.split('/')[2];
$('#search-input').attr('value', toBeSearched);
var myArray = <?php echo json_encode($products_merged) ?>;
$(document).ready(function(){
console.log('Url keyword: ', toBeSearched);
var data = searchTable(toBeSearched, myArray);
buildTable(data);
(function(name) {
var container = $('#pagination-' + name);
container.pagination({
dataSource: data,
locator: 'dataSource',
totalNumber: 50,
pageSize: 20,
showPageNumbers: true,
showPrevious: true,
showNext: true,
showNavigator: true,
showFirstOnEllipsisShow: true,
showLastOnEllipsisShow: true,
ajax: {
beforeSend: function() {
container.prev().html('Loading...');
}
},
callback: function(response, pagination) {
window.console && console.log(22, response, pagination);
var dataHtml = '';
$.each(response, function (index, dataSource) {
dataHtml +=
'<div style="border: 1px solid #888888; border-radius: 5px; margin: 15px;" class="col-md-2">'
+ '<div class="card-body">'
+ '<b>'+ dataSource.title +'</b></h5>'
+ 'Vezi specificatii'
+ '</div>'
+ '</div>';
});
dataHtml += '';
container.prev().html(dataHtml);
}
})
})('demo');
});
$('#search-input').on('keyup', function(){
var value = $(this).val();
console.log('value: ', value);
var data = searchTable(value, myArray);
buildTable(data);
(function(name) {
var container = $('#pagination-' + name);
container.pagination({
dataSource: data,
locator: 'dataSource',
totalNumber: 50,
pageSize: 20,
showPageNumbers: true,
showPrevious: true,
showNext: true,
showNavigator: true,
showFirstOnEllipsisShow: true,
showLastOnEllipsisShow: true,
ajax: {
beforeSend: function() {
container.prev().html('Loading data from db...');
}
},
callback: function(response, pagination) {
window.console && console.log(22, response, pagination);
var dataHtml = '';
$.each(response, function (index, dataSource) {
dataHtml +=
'<div style="border: 1px solid #888888; border-radius: 5px; margin: 15px;" class="col-md-2">'
+ '<div class="card-body">'
+ '<b>'+ dataSource.title +'</b></h5>'
+ 'Vezi specificatii'
+ '</div>'
+ '</div>';
});
dataHtml += '';
container.prev().html(dataHtml);
}
})
})('demo');
});
$(function(){
if(toBeSearched === undefined){
buildTable(myArray);
(function(name) {
var container = $('#pagination-' + name);
container.pagination({
dataSource: myArray,
locator: 'dataSource',
totalNumber: 50,
pageSize: 20,
showPageNumbers: true,
showPrevious: true,
showNext: true,
showNavigator: true,
showFirstOnEllipsisShow: true,
showLastOnEllipsisShow: true,
ajax: {
beforeSend: function() {
container.prev().html('Loading...');
}
},
callback: function(response, pagination) {
window.console && console.log(22, response, pagination);
var dataHtml = '';
$.each(response, function (index, dataSource) {
dataHtml +=
'<div style="border: 1px solid #888888; border-radius: 5px; margin: 15px;" class="col-md-2">'
+ '<div class="card-body">'
+ '<b>'+ dataSource.title +'</b></h5>'
+ 'Vezi specificatii'
+ '</div>'
+ '</div>';
});
dataHtml += '';
container.prev().html(dataHtml);
}
})
})('demo');
}
});
function searchTable(value, data){
var filteredData = [];
for(var i = 0; i < data.length; i++){
value = value.toLowerCase();
var name = data[i].title.toLowerCase();
if(name.includes(value)){
filteredData.push(data[i])
}
}
return filteredData;
}
function buildTable(data){
var table = document.getElementById('myTable');
table.innerHTML = '';
for (var i = 0; i < data.length; i++){
var row = `<tr>
<td>${data[i].title}</td>
<td></td>
<td></td>
</tr>`;
table.innerHTML += row;
}
};
</script>
My question would be which architectural solutions i could go towards or how can I improve my code so it can be more efficient.
PS: I tried doing it first with php submission by grabbing the url and I was ending up in infinite loop using header on processing page.

How on Ajax request genereate once divs for data and then on next ajax request update only the data in the divs?

Hi there I'm trying to populate div with data from ajax request, the idea is to use Ajax to get temperature from multiple sensors and for every sensor temperature data I want a separate div column with the data, So on document.ready I use ajax get once to popualte the main page div with the div columns to get the results, but after that I want to use ajax again every 10 seconds to update the data, but how can I do it not generating the containers for the data again? Because of waht I have right now I can't make it to work when I try to make a filter to show/hide the div for specific location.
$(document).ready(function(){
var menu_list = [];
var tr_str = [];
var temp_int= [];
$.ajax({
url: 'getData.php',
type: 'get',
dataType: 'JSON',
success: function(response){
var len = response.length;
for(var i=0; i<len; i++){
var location = response[i].location;
temp_int[i] = response[i].temp_int;
var temp = response[i].temp;
var hum = response[i].hum;
var dew = response[i].dew;
tr_str[i] = "<div id='locc" + i + "' class='location'>" +
"<span class='title'>" + location + "</span>" +
"<div class='temp" + i + "'><span>Temperatura: </span><span id='check'>" + temp + " &degC</span></div>" +
"<div><span>Względna wilgotność: </span><span>" + hum + " %RH</span></div>" +
"<div><span>Punkt rosy: </span><span>" + dew + " &degC</span></div>" +
"</div>";
menu_list[i] = "<label for='loc" + i + "'>" +
"<input type='checkbox' id='loc" + i + "' checked='checked'/>" +
"<span class='css-checkbox'></span>" +
"<p>" + location + "</p>" +
"</label>";
}
$("#nav").append(menu_list);
$("#data").html(tr_str);
for(var i=0; i<len; i++){
if (temp_int[i] >= 250) {
$(".temp" + i).css("background-color", "#ff0000");
}
else if (temp_int[i] >= 235) {
$('.temp' + i).css("background-color","#f1c40f");
}
else {
$('.temp' +i).css("background-color","#3498db");
}
}
}
});
$("#loc1").change(function () {
if (this.checked){
$("#locc1").show(!this.checked);
}else {
$("#locc1").hide(!this.checked);
}
});
});
setTimeout(fetchdata,5000);
function fetchdata(){
var tr_str = [];
var temp_int= [];
$.ajax({
url: 'getData.php',
type: 'get',
dataType: 'JSON',
cache: false,
success: function(response){
var len = response.length;
for(var i=0; i<len; i++){
var location = response[i].location;
temp_int[i] = response[i].temp_int;
var temp = response[i].temp;
var hum = response[i].hum;
var dew = response[i].dew;
tr_str[i] = "<div id='locc" + i + "' class='location'>" +
"<span class='title'>" + location + "</span>" +
"<div class='temp" + i + "'><span>Temperatura: </span><span id='check'>" + temp + " &degC</span></div>" +
"<div><span>Względna wilgotność: </span><span>" + hum + " %RH</span></div>" +
"<div><span>Punkt rosy: </span><span>" + dew + " &degC</span></div>" +
"</div>";
}
$("#data").html(tr_str);
for(var i=0; i<len; i++){
if (temp_int[i] >= 250) {
$(".temp" + i).css("background-color", "#ff0000");
}
else if (temp_int[i] >= 235) {
$('.temp' + i).css("background-color","#f1c40f");
}
else {
$('.temp' +i).css("background-color","#3498db");
}
}
},
complete:function(){
setTimeout(fetchdata,5000);
}
});
}
function openNav() {
document.getElementById("nav").style.width = "350px";
document.getElementById("data").style.marginLeft = "350px";
}
function closeNav() {
document.getElementById("nav").style.width = "0";
document.getElementById("data").style.marginLeft = "0";
}
<!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>Document</title>
<link rel="stylesheet" href="lib/style.css">
</head>
<body>
<div id="nav" class="menu">
×
<button>Uncheck all</button>
</div>
<div class="nav-wrapper">
<span onclick="openNav()">☰</span>
</div>
<div id="data" class="wrapper"></div>
</body>
</html>
You can see that I use almost the same Ajax request again, is there a way to get teh data at first and generate the divs for the data and then just get the data every 10 seconds and update it only withou generating again the divs?
I'm thinking that what I have right now is making tis unable to work
var $checkboxes = $("#nav :checkbox");
var $button = $("#nav button");
function allChecked(){
return $checkboxes.length === $checkboxes.filter(":checked").length;
}
function updateButtonStatus(){
$button.text(allChecked()? "Uncheck all" : "Check all");
}
function handleButtonClick(){
$checkboxes.prop("checked", allChecked()? false : true)
}
$button.on("click", function() {
handleButtonClick();
updateButtonStatus();
checking();
});
$checkboxes.on("change", function(){
updateButtonStatus();
});
function openNav() {
document.getElementById("nav").style.width = "250px";
}
function closeNav() {
document.getElementById("nav").style.width = "0";
}
function checking() {
var temps = <?php echo json_encode($temps); ?>; //I know this is wrong I would change the loop iteration but it is not working even for one static element when I change it.
$.each( temps, function( index, value ){
$('#loc'+index).change(function () {
if( this.checked ) {
$('#locc'+index).show(!this.checked);
} else {
$('#locc'+index).hide(!this.checked);
}
}).change();
});}
Here is the php file code I'm geting using ajax:
<?php
require 'lib/locations.php';
$search = array('STRING: ', '"');
$search2 = array('INTEGER: ', '"');
$replace = array('','');
$return_arr = array();
for ($i = 0; $i < $c; $i++) {
$temp_int = snmpget($ips[$i], $community, ".1.3.6.1.4.1.22626.1.2.3.1.0");
$temp_int = str_replace($search2,$replace,$temp_int);
$temp = snmpget($ips[$i], $community, ".1.3.6.1.4.1.22626.1.2.1.1.0");
$temp = str_replace($search,$replace,$temp);
$hum = snmpget($ips[$i], $community, ".1.3.6.1.4.1.22626.1.2.1.2.0");
$hum = str_replace($search,$replace,$hum);
$dew = snmpget($ips[$i], $community, ".1.3.6.1.4.1.22626.1.2.1.3.0");
$dew = str_replace($search,$replace,$dew);
$loc = $location[$i];
$return_arr[] = array("location" => $loc,
"temp_int" => $temp_int,
"temp" => $temp,
"hum" => $hum,
"dew" => $dew);
}
echo json_encode($return_arr);
?>
The generated data is an array of one integer and strings
something like this:
var response =[{
"location": "location_1"
"temp_int":250,
"temp":"30.5",
"hum":"49.8",
"dew":"8.5"
},
{"location": "location_1"
"temp_int":250,
"temp":"30.5",
"hum":"49.8",
"dew":"8.5"
}, etc.]

.replacewith not working when called a second time

I have the following markup:
<fieldset>
<legend>Headline Events...</legend>
<div style="width:100%; margin-top:10px;">
<div style="width:100%; float:none;" class="clear-fix">
<div style="width:400px; float:left; margin-bottom:8px;">
<div style="width:150px; float:left; text-align:right; padding-top:7px;">
Team Filter:
</div>
<div style="width:250px; float:left;">
<input id="teamFilter" style="width: 100%" />
</div>
</div>
<div style="width:400px; float:left; margin-bottom:8px;">
<div style="width:150px; float:left; text-align:right; padding-top:7px;">
Type Filter:
</div>
<div style="width:250px; float:left;">
<input id="typeFilter" style="width: 100%" />
</div>
</div>
</div>
</div>
<div id="diaryTable" name="diaryTable" class="clear-fix">
Getting latest Headlines...
</div>
</fieldset>
I also have the following scripts
<script>
function teamFilterChange(e) {
//alert(this.value());
setCookie('c_team', this.value(), 90);
$c1 = getCookie('c_team');
$c2 = getCookie('c_type');
var param = "true|" + $c1 + "|" + $c2;
outputHLDiaryEntries(param);
}
function typeFilterChange(e) {
//alert(this.value());
setCookie('c_type', this.value(), 90);
$c1 = getCookie('c_team');
$c2 = getCookie('c_type');
var param = "true|" + $c1 + "|" + $c2;
outputHLDiaryEntries(param);
}
// This optional function html-encodes messages for display in the page.
function htmlEncode(value) {
var encodedValue = $('<div />').text(value).html();
return encodedValue;
}
function outputHLDiaryEntries(param) {
var url = "Home/DiaryEntries/";
var data = "id=" + param;
$.post(url, data, function (json) {
var n = json.length;
alert(n + ' ' + json);
if(n == 0){
//json is 0 length this happens when there were no errors and there were no results
$('#diaryTable').replaceWith("<span style='color:#e00;'><strong>Sorry: </strong> There are no headline events found. Check your filters.</span>");
} else {
//json has a length so it may be results or an error message
//if jsom[0].dID is undefined then this mean that json contains the error message from an exception
if (typeof json[0].dID != 'undefined') {
//json[0].dDI has a value so we
//output the json formatted results
var out = "";
var i;
var a = "N" //used to change the class for Normal and Alternate rows
for (i = 0; i < json.length; i++) {
out += '<div class="dOuter' + a + '">';
out += '<div class="dInner">' + json[i].dDate + '</div>';
out += '<div class="dInner">' + json[i].dRef + '</div>';
out += '<div class="dInner">' + json[i].dTeam + '</div>';
out += '<div class="dInner">' + json[i].dCreatedBy + '</div>';
out += '<div class="dType ' + json[i].dType + '">' + json[i].dType + '</div>';
out += '<div class="dServer">' + json[i].dServer + '</div>';
out += '<div class="dComment">' + htmlEncode(json[i].dComment) + '</div></div>';
//toggle for normal - alternate rows
if (a == "N") {
a = "A";
} else {
a = "N";
}
}
//output our formated data to the diaryTable div
$('#diaryTable').replaceWith(out);
} else {
//error so output json string
$('#diaryTable').replaceWith(json);
}
}
}, 'json');
}
$(document).ready(function () {
//Set User Preferences
//First check cookies and if null or empty set to default values
var $c1 = getCookie('c_team');
if ($c1 == "") {
//team cookie does not exists or has expired
setCookie('c_team', 'ALL', 90);
$c1 = "ALL";
}
var $c2 = getCookie('c_type');
if ($c2 == "") {
//type cookie does not exists or has expired
setCookie('c_type', "ALL", 90);
$c2 = "ALL";
}
// create DropDownList from input HTML element
//teamFilter
$("#teamFilter").kendoDropDownList({
dataTextField: "SupportTeamText",
dataValueField: "SupportTeamValue",
dataSource: {
transport: {
read: {
dataType: "json",
url: "Home/SupportTeams?i=1",
}
}
}
});
var teamFilter = $("#teamFilter").data("kendoDropDownList");
teamFilter.bind("change", teamFilterChange);
teamFilter.value($c1);
//typeFilter
$("#typeFilter").kendoDropDownList({
dataTextField: "dTypeText",
dataValueField: "dTypeValue",
dataSource: {
transport: {
read: {
dataType: "json",
url: "Home/DiaryTypes?i=1",
}
}
}
});
var typeFilter = $("#typeFilter").data("kendoDropDownList");
typeFilter.bind("change", typeFilterChange);
typeFilter.value($c2);
// Save the reference to the SignalR hub
var dHub = $.connection.DiaryHub;
// Invoke the function to be called back from the server
// when changes are detected
// Create a function that the hub can call back to display new diary HiLights.
dHub.client.addNewDiaryHiLiteToPage = function (name, message) {
// Add the message to the page.
$('#discussion').append('<li><strong>' + htmlEncode(name)
+ '</strong>: ' + htmlEncode(message) + '</li>');
};
// Start the SignalR client-side listener
$.connection.hub.start().done(function () {
// Do here any initialization work you may need
var param = "true|" + $c1 + "|" + $c2;
outputHLDiaryEntries(param)
});
});
</script>
On initial page load the outputHLDiaryEntries function is called when the signalR hub is started. If I then change any of the dropdownlists this calls the outputHLDiaryEntries but the $('#diaryTable').replaceWith(); does not work. If I refresh the page the correct data is displayed.
UPDATE!
Based on A.Wolff's comments I fixed the issue by wrapping the content I needed with the same element I was replacing... by adding the following line at the beginning of the outputHLDiartEntries function...
var outStart = '<div id="diaryTable" name="diaryTable" class="clear-fix">';
var outEnd = '</div>';
and then changing each of the replaceWith so that they included the wrappers e.g.
$('#diaryTable').replaceWith(outStart + out + outEnd);
replaceWith() replaces element itself, so then on any next call to $('#diaryTable') will return empty matched set.
You best bet is to replace element's content instead, e.g:
$('#diaryTable').html("<span>New content</span>");
I had the same problem with replaceWith() not working when called a second time.
This answer helped me figure out what I was doing wrong.
The change I made was assigning the same id to the new table I was creating.
Then when I would call my update function again, it would create a new table, assign it the same id, grab the previous table by the id, and replace it.
let newTable = document.createElement('table');
newTable.id = "sameId";
//do the work to create the table here
let oldTable = document.getElementById('sameId');
oldTable.replaceWith(newTable);

Create table with jQuery - append

I have on page div:
<div id="here_table"></div>
and in jquery:
for(i=0;i<3;i++){
$('#here_table').append( 'result' + i );
}
this generating for me:
<div id="here_table">
result1 result2 result3 etc
</div>
I would like receive this in table:
<div id="here_table">
<table>
<tr><td>result1</td></tr>
<tr><td>result2</td></tr>
<tr><td>result3</td></tr>
</table>
</div>
I doing:
$('#here_table').append( '<table>' );
for(i=0;i<3;i++){
$('#here_table').append( '<tr><td>' + 'result' + i + '</td></tr>' );
}
$('#here_table').append( '</table>' );
but this generate for me:
<div id="here_table">
<table> </table> !!!!!!!!!!
<tr><td>result1</td></tr>
<tr><td>result2</td></tr>
<tr><td>result3</td></tr>
</div>
Why? how can i make this correctly?
LIVE: http://jsfiddle.net/n7cyE/
This line:
$('#here_table').append( '<tr><td>' + 'result' + i + '</td></tr>' );
Appends to the div#here_table not the new table.
There are several approaches:
/* Note that the whole content variable is just a string */
var content = "<table>"
for(i=0; i<3; i++){
content += '<tr><td>' + 'result ' + i + '</td></tr>';
}
content += "</table>"
$('#here_table').append(content);
But, with the above approach it is less manageable to add styles and do stuff dynamically with <table>.
But how about this one, it does what you expect nearly great:
var table = $('<table>').addClass('foo');
for(i=0; i<3; i++){
var row = $('<tr>').addClass('bar').text('result ' + i);
table.append(row);
}
$('#here_table').append(table);
Hope this would help.
You need to append the tr inside the table so I updated your selector inside your loop and removed the closing table because it is not necessary.
$('#here_table').append( '<table />' );
for(i=0;i<3;i++){
$('#here_table table').append( '<tr><td>' + 'result' + i + '</td></tr>' );
}
The main problem was that you were appending the tr to the div here_table.
Edit: Here is a JavaScript version if performance is a concern. Using document fragment will not cause a reflow for every iteration of the loop
var doc = document;
var fragment = doc.createDocumentFragment();
for (i = 0; i < 3; i++) {
var tr = doc.createElement("tr");
var td = doc.createElement("td");
td.innerHTML = "content";
tr.appendChild(td);
//does not trigger reflow
fragment.appendChild(tr);
}
var table = doc.createElement("table");
table.appendChild(fragment);
doc.getElementById("here_table").appendChild(table);
When you use append, jQuery expects it to be well-formed HTML (plain text counts). append is not like doing +=.
You need to make the table first, then append it.
var $table = $('<table/>');
for(var i=0; i<3; i++){
$table.append( '<tr><td>' + 'result' + i + '</td></tr>' );
}
$('#here_table').append($table);
Or do it this way to use ALL jQuery. The each can loop through any data be it DOM elements or an array/object.
var data = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight'];
var numCols = 1;
$.each(data, function(i) {
if(!(i%numCols)) tRow = $('<tr>');
tCell = $('<td>').html(data[i]);
$('table').append(tRow.append(tCell));
});
​
http://jsfiddle.net/n7cyE/93/
To add multiple columns and rows, we can also do a string concatenation. Not the best way, but it sure works.
var resultstring='<table>';
for(var j=0;j<arr.length;j++){
//array arr contains the field names in this case
resultstring+= '<th>'+ arr[j] + '</th>';
}
$(resultset).each(function(i, result) {
// resultset is in json format
resultstring+='<tr>';
for(var j=0;j<arr.length;j++){
resultstring+='<td>'+ result[arr[j]]+ '</td>';
}
resultstring+='</tr>';
});
resultstring+='</table>';
$('#resultdisplay').html(resultstring);
This also allows you to add rows and columns to the table dynamically, without hardcoding the fieldnames.
Here is what you can do: http://jsfiddle.net/n7cyE/4/
$('#here_table').append('<table></table>');
var table = $('#here_table').children();
for(i=0;i<3;i++){
table.append( '<tr><td>' + 'result' + i + '</td></tr>' );
}
Best regards!
Following is done for multiple file uploads using jquery:
File input button:
<div>
<input type="file" name="uploadFiles" id="uploadFiles" multiple="multiple" class="input-xlarge" onchange="getFileSizeandName(this);"/>
</div>
Displaying File name and File size in a table:
<div id="uploadMultipleFilediv">
<table id="uploadTable" class="table table-striped table-bordered table-condensed"></table></div>
Javascript for getting the file name and file size:
function getFileSizeandName(input)
{
var select = $('#uploadTable');
//select.empty();
var totalsizeOfUploadFiles = "";
for(var i =0; i<input.files.length; i++)
{
var filesizeInBytes = input.files[i].size; // file size in bytes
var filesizeInMB = (filesizeInBytes / (1024*1024)).toFixed(2); // convert the file size from bytes to mb
var filename = input.files[i].name;
select.append($('<tr><td>'+filename+'</td><td>'+filesizeInMB+'</td></tr>'));
totalsizeOfUploadFiles = totalsizeOfUploadFiles+filesizeInMB;
//alert("File name is : "+filename+" || size : "+filesizeInMB+" MB || size : "+filesizeInBytes+" Bytes");
}
}
Or static HTML without the loop for creating some links (or whatever). Place the <div id="menu"> on any page to reproduce the HTML.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>HTML Masterpage</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
function nav() {
var menuHTML= '<ul><li>link 1</li></ul><ul><li>link 2</li></ul>';
$('#menu').append(menuHTML);
}
</script>
<style type="text/css">
</style>
</head>
<body onload="nav()">
<div id="menu"></div>
</body>
</html>
I wrote rather good function that can generate vertical and horizontal tables:
function generateTable(rowsData, titles, type, _class) {
var $table = $("<table>").addClass(_class);
var $tbody = $("<tbody>").appendTo($table);
if (type == 2) {//vertical table
if (rowsData.length !== titles.length) {
console.error('rows and data rows count doesent match');
return false;
}
titles.forEach(function (title, index) {
var $tr = $("<tr>");
$("<th>").html(title).appendTo($tr);
var rows = rowsData[index];
rows.forEach(function (html) {
$("<td>").html(html).appendTo($tr);
});
$tr.appendTo($tbody);
});
} else if (type == 1) {//horsantal table
var valid = true;
rowsData.forEach(function (row) {
if (!row) {
valid = false;
return;
}
if (row.length !== titles.length) {
valid = false;
return;
}
});
if (!valid) {
console.error('rows and data rows count doesent match');
return false;
}
var $tr = $("<tr>");
titles.forEach(function (title, index) {
$("<th>").html(title).appendTo($tr);
});
$tr.appendTo($tbody);
rowsData.forEach(function (row, index) {
var $tr = $("<tr>");
row.forEach(function (html) {
$("<td>").html(html).appendTo($tr);
});
$tr.appendTo($tbody);
});
}
return $table;
}
usage example:
var title = [
'مساحت موجود',
'مساحت باقیمانده',
'مساحت در طرح'
];
var rows = [
[number_format(data.source.area,2)],
[number_format(data.intersection.area,2)],
[number_format(data.deference.area,2)]
];
var $ft = generateTable(rows, title, 2,"table table-striped table-hover table-bordered");
$ft.appendTo( GroupAnalyse.$results );
var title = [
'جهت',
'اندازه قبلی',
'اندازه فعلی',
'وضعیت',
'میزان عقب نشینی',
];
var rows = data.edgesData.map(function (r) {
return [
r.directionText,
r.lineLength,
r.newLineLength,
r.stateText,
r.lineLengthDifference
];
});
var $et = generateTable(rows, title, 1,"table table-striped table-hover table-bordered");
$et.appendTo( GroupAnalyse.$results );
$('<hr/>').appendTo( GroupAnalyse.$results );
example result:
A working example using the method mentioned above and using JSON to represent the data. This is used in my project of dealing with ajax calls fetching data from server.
http://jsfiddle.net/vinocui/22mX6/1/
In your html:
< table id='here_table' >< /table >
JS code:
function feed_table(tableobj){
// data is a JSON object with
//{'id': 'table id',
// 'header':[{'a': 'Asset Tpe', 'b' : 'Description', 'c' : 'Assets Value', 'd':'Action'}],
// 'data': [{'a': 'Non Real Estate', 'b' :'Credit card', 'c' :'$5000' , 'd': 'Edit/Delete' },... ]}
$('#' + tableobj.id).html( '' );
$.each([tableobj.header, tableobj.data], function(_index, _obj){
$.each(_obj, function(index, row){
var line = "";
$.each(row, function(key, value){
if(0 === _index){
line += '<th>' + value + '</th>';
}else{
line += '<td>' + value + '</td>';
}
});
line = '<tr>' + line + '</tr>';
$('#' + tableobj.id).append(line);
});
});
}
// testing
$(function(){
var t = {
'id': 'here_table',
'header':[{'a': 'Asset Tpe', 'b' : 'Description', 'c' : 'Assets Value', 'd':'Action'}],
'data': [{'a': 'Non Real Estate', 'b' :'Credit card', 'c' :'$5000' , 'd': 'Edit/Delete' },
{'a': 'Real Estate', 'b' :'Property', 'c' :'$500000' , 'd': 'Edit/Delete' }
]};
feed_table(t);
});
As for me, this approach is prettier:
String.prototype.embraceWith = function(tag) {
return "<" + tag + ">" + this + "</" + tag + ">";
};
var results = [
{type:"Fiat", model:500, color:"white"},
{type:"Mercedes", model: "Benz", color:"black"},
{type:"BMV", model: "X6", color:"black"}
];
var tableHeader = ("Type".embraceWith("th") + "Model".embraceWith("th") + "Color".embraceWith("th")).embraceWith("tr");
var tableBody = results.map(function(item) {
return (item.type.embraceWith("td") + item.model.toString().embraceWith("td") + item.color.embraceWith("td")).embraceWith("tr")
}).join("");
var table = (tableHeader + tableBody).embraceWith("table");
$("#result-holder").append(table);
i prefer the most readable and extensible way using jquery.
Also, you can build fully dynamic content on the fly.
Since jquery version 1.4 you can pass attributes to elements which is, imho, a killer feature.
Also the code can be kept cleaner.
$(function(){
var tablerows = new Array();
$.each(['result1', 'result2', 'result3'], function( index, value ) {
tablerows.push('<tr><td>' + value + '</td></tr>');
});
var table = $('<table/>', {
html: tablerows
});
var div = $('<div/>', {
id: 'here_table',
html: table
});
$('body').append(div);
});
Addon: passing more than one "html" tag you've to use array notation like:
e.g.
var div = $('<div/>', {
id: 'here_table',
html: [ div1, div2, table ]
});
best Rgds.
Franz
<table id="game_table" border="1">
and Jquery
var i;
for (i = 0; ii < 10; i++)
{
var tr = $("<tr></tr>")
var ii;
for (ii = 0; ii < 10; ii++)
{
tr.append(`<th>Firstname</th>`)
}
$('#game_table').append(tr)
}
this is most better
html
<div id="here_table"> </div>
jQuery
$('#here_table').append( '<table>' );
for(i=0;i<3;i++)
{
$('#here_table').append( '<tr>' + 'result' + i + '</tr>' );
for(ii=0;ii<3;ii++)
{
$('#here_table').append( '<td>' + 'result' + i + '</tr>' );
}
}
$('#here_table').append( '</table>' );
It is important to note that you could use Emmet to achieve the same result. First, check what Emmet can do for you at https://emmet.io/
In a nutshell, with Emmet, you can expand a string into a complexe HTML markup as shown in the examples below:
Example #1
ul>li*5
... will produce
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
Example #2
div#header+div.page+div#footer.class1.class2.class3
... will produce
<div id="header"></div>
<div class="page"></div>
<div id="footer" class="class1 class2 class3"></div>
And list goes on. There are more examples at https://docs.emmet.io/abbreviations/syntax/
And there is a library for doing that using jQuery. It's called Emmet.js and available at https://github.com/christiansandor/Emmet.js
Here the below code helps to generate responsive html table
#javascript
(function($){
var data = [{
"head 1": "row1 col 1",
"head 2": "row1 col 2",
"head 3": "row1 col 3"
}, {
"head 1": "row2 col 1",
"head 2": "row2 col 2",
"head 3": "row2 col 3"
}, {
"head 1": "row3 col 1",
"head 2": "row3 col 2",
"head 3": "row3 col 3"
}];
for (var i = 0; i < data.length; i++) {
var accordianhtml = "<button class='accordion'>" + data[i][small_screen_heading] + "<span class='arrow rarrow'>→</span><span class='arrow darrow'>↓</span></button><div class='panel'><p><table class='accordian_table'>";
var table_row = null;
var table_header = null;
for (var key in data[i]) {
accordianhtml = accordianhtml + "<tr><th>" + key + "</th><td>" + data[i][key] + "</td></tr>";
if (i === 0 && true) {
table_header = table_header + "<th>" + key + "</th>";
}
table_row = table_row + "<td>" + data[i][key] + "</td>"
}
if (i === 0 && true) {
table_header = "<tr>" + table_header + "</tr>";
$(".mv_table #simple_table").append(table_header);
}
table_row = "<tr>" + table_row + "</tr>";
$(".mv_table #simple_table").append(table_row);
accordianhtml = accordianhtml + "</table></p></div>";
$(".mv_table .accordian_content").append(accordianhtml);
}
}(jquery)
Here we can see the demo responsive html table generator
let html = '';
html += '<table class="tblWay" border="0" cellpadding="5" cellspacing="0" width="100%">';
html += '<tbody>';
html += '<tr style="background-color:#EEEFF0">';
html += '<td width="80"> </td>';
html += '<td><b>Shipping Method</b></td>';
html += '<td><b>Shipping Cost</b></td>';
html += '<td><b>Transit Time</b></td>';
html += '</tr>';
html += '</tbody>';
html += '</table>';
$('.product-shipping-more').append(html);

Categories

Resources