I'm trying display list of institutions from my API, where I want to display only 10 and when load more button is clicked it should display remaining and load more button contain nextpage url i.e., remaining list in json format
html code is as follows
<div class="container text-center">
<h1 class="text-center">Existing Institutions </h1>
<div class="row row-centered">
<div class="col-md-10 col-md-offset-1">
<div class="col-md-12">
<div class="table-responsive">
<table id="claimList" class="table table-bordered table-hover table-striped tablesorter">
<thead>
<tr>
<th class="header"> Institute Name <i class="icon-sort"></i></th>
<th class="header"> Address <i class="icon-sort"></i></th>
<th class="header"> Location <i class="icon-sort"></i></th>
</tr>
</thead>
<tbody>
{% for key in data %}
<tr>
<td>{{ key.displayName }}</td>
<td>{{ key.businessAddress }}</td>
<td>{{ key.businessLocation }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<ul class="pager">
<li class="next"><button name="load_more" id="load_more" onsubmit="loadMore({{ nextPage }});">Load More</button></li>
</ul>
</div>
</div>
</div>
</div>
</div>
my ajax code is
function loadMore(url) {
alert(url);
$.ajax({
dataType: "json",
url: url,
success: function (data) {
alert(data);
var table = document.getElementById("claimList");
for (var i=0; i < data.length; i++) {
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell3.style.width = '25px';
cell1.innerHTML = '<td>{{ data.displayName }}</td>';
cell2.innerHTML = '<td>{{ data.businessAddress }}</td>';
cell3.innerHTML = '<td>{{ data.businessLocation }}</td>';
}
},
error: function (request, error) {
console.log(arguments);
alert(" Can't load more because " + error);
},
});
}
i'm getting the data which resides in data. now how to parse data and display in the html table
data table integration
put it in HTML make sure jquery is added.
https://cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css
https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js
<table class="table table-bordered table-condensed details">
<input type="hidden" name="data_source_url" value="{% url'institutions'%}"
<thead>
<tr>
<th class="header"> Institute Name <i class="icon-sort"></i></th>
<th class="header"> Address <i class="icon-sort"></i></th>
<th class="header"> Location <i class="icon-sort"></i></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
javascript:
$(document).ready(function() {
$("a.toggle_hidden_details").on("click", function(e) {
var top_div = $(this).closest('div.td_details');
var hidden_div = top_div.find('div.hidden_details');
var icon = top_div.find('i')
if (hidden_div.is(':visible')) {
hidden_div.slideUp();
icon.removeClass('icon-minus');
icon.addClass('icon-plus');
} else {
hidden_div.slideDown();
icon.removeClass('icon-plus');
icon.addClass('icon-minus');
}
});
if ($("input[name='data_source_url']").length > 0) {
var source = $("input[name='data_source_url']").val();
$('table.admin_details').dataTable({
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": source
});
} else {
$('table.details').dataTable();
}
datatable integration in views.py make sure have added the urls for this.
import json
def issue_history_data(request):
search = request.GET.get("sSearch")
institutions = MODEL_NAME.objects.all()
institutions_list = list(set(institutions))
# ordering
sort_column = int(request.GET.get("iSortCol_0"))
sort_dir = request.GET.get("sSortDir_0")
# page filter
start = request.GET.get("iDisplayStart")
length = request.GET.get("iDisplayLength")
instituties = institutions_list
if length != -1:
page = int(start) // int(length) + 1 if start else 1
paginator = Paginator(institutions_list, length)
issues = paginator.page(page)
institutionsData = []
for insti in instituties:
try:
institutionsData.append([
'name',
insti.businessAddress,
insti.businessLocation,
])
except Exception as e:
log.debug('possible bad issue' + str(issue.pk), exc_info=True)
returnDict = {
"sEcho": request.GET.get("sEcho"),
"iTotalRecords": len(institutions_list),
"iTotalDisplayRecords": len(institutions_list),
"aaData": institutionsData
}
return HttpResponse(json.dumps(returnDict))
If you want to load content on the go, you should use AJAX, and since you're using jQuery, you can use jQuery.getJSON(URL, callback).
function loadMore(page) {
// This is assuming that your data is at the specified path
// you should edit it to fit your needs.
$.getJSON('/path/to/data?page=' + page, function (data) {
/* Process the data */
});
}
Related
I want to take data from my local storage and show it dynamically. In this table below is the code that I tried but it is not working.
<script>
var cart= JSON.parse( localStorage.getItem('Mylinklist'));
$.each(Mylinklist, function(key, value){
$('tbody').append(`<tr>
<td>${cart.name}</td>
<td>${cart.url}</td>
</tr>`)
})
</script>
<div id="actionerpanel" class="col col-lg-6 col-12 ">
<div class="rapi-card m-lg-5 m-1">
<b class="rapi-card-colored-header p-3 mb-2">Quick Links <span>+</span></b>
<div class="container">
<div class="row justify-content-center "><table class="table">
<thead>
<tr>
<th scope="col">Link Name</th>
<th scope="col">Url</th>
<th scope="col">Actions</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
You can use insertAdjacentHTML and literals templates for this kind of operation.
var carts = [{
id: 'id1',
name: 'test',
url: 'url'
}, {
id: 'id2',
name: 'test2',
url: 'url2'
}] //Fake localstorage replace it with JSON.parse
carts.forEach(cart => {
let button = `<button onclick="alert('Item id : ${cart.id}')">Click</button>`,
row = `<tr id="item_${cart.id}"><td>${cart.name}</td><td>${cart.url}</td><td>${button}</td></tr>`;
document.querySelector('tbody').insertAdjacentHTML('beforeend', row)
})
//OR
for (let cart of carts) {
let button = `<button onclick="alert('Item id : ${cart.id}')">Click</button>`,
row = `<tr id="item_${cart.id}"><td>${cart.name}</td><td>${cart.url}</td><td>${button}</td></tr>`;
document.querySelector('tbody').insertAdjacentHTML('beforeend', row)
}
<table class="table">
<thead>
<tr>
<th scope="col">Link Name</th>
<th scope="col">Url</th>
<th scope="col">Actions</th>
</tr>
</thead>
<tbody></tbody>
</table>
You can make it with plain JS like this. I had to comment out the places with localstorage. Because access to localStorage is not allowed on SO. As soon as you add them, it works.
const arr = [
{id: 123, name: "google", url: "https://www.google.com"},
{id: 124, name: "bing", url: "https://www.bing.com"},
]
// store to localStorage
// localStorage.setItem('Mylinklist', JSON.stringify(arr));
// get from localStorage
// const data = JSON.parse(localStorage.getItem('Mylinklist'));
const table = document.querySelector('.table');
// change obj.forEach to data.forEach because in SO you cant use localStorage!!!
arr.forEach((e) => {
let tr = document.createElement('TR');
let td_name = document.createElement('TD');
let td_url = document.createElement('TD');
td_name.innerHTML = e.name
td_url.innerHTML = e.url
tr.append(td_name)
tr.append(td_url)
table.append(tr)
})
<div class="row justify-content-center "><table class="table">
<thead>
<tr>
<th scope="col">Link Name</th>
<th scope="col">Url</th>
<th scope="col">Actions</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
I'm beginner in developing.
I followed this tutorial (https://www.youtube.com/watch?v=hy4mvRToYQA&ab_channel=Webslesson) which make search function with multiple tags.
here below is my code for search bar:
<div class="row">
<div class="col-md-10">
<input type="text" id="tags" class="form-control" data-role="tagsinput" />
</div>
<div class="col-md-2">
<button type="button" name="search" class="btn btn-primary" id="search">>>SEARCH</button>
</div>
</div>
<br>
<div class="table-responsive">
<div allign="right">
<p><b>Total Records - <span id="total_records"></span></b></p>
</div>
<table class="table table-bordered table-striped">
<thread>
<tr>
<th>No.</th>
<th>BRAND</th>
<th>SHOE STYLE</th>
<th>COLOR</th>
<th>SHOE IMAGE</th>
<th>SG SHOE ID</th>
<th>CUST SHOE ID</th>
<th>PD TYPE</th>
<th>SIZE TYPE</th>
</tr>
</thread>
<tbody>
</tbody>
</table>
</div>
and this is the code I put for function:
<script>
$(document).ready(function(){
load_data();
function load_data(query)
{
$.ajax({
url:"fetch_pd_list.php",
method: "post",
data:{query:query},
dataType: "json",
success: function(data){
// $('#total_records').text(data.length);
var html = '';
if ($(data) == null) {data.length = 0};
if (data.length > 0) {
for(var count = 0; count < data.length; count++) {
html += '<tr>';
html += '<td>'+data[count].no+'</td>';
html += '<td>'+data[count].brand_name+'</td>';
html += '<td>'+data[count].style_name+'</td>';
html += '<td>'+data[count].color_name+'</td>';
html += '<td>'+data[count].pd_image+'</td>';
html += '<td>'+data[count].sg_code+'</td>';
html += '<td>'+data[count].cust_code+'</td>';
html += '<td>'+data[count].production_type+'</td>';
html += '<td>'+data[count].size_type_name+'</td></tr>';
}
} else {
html = '<tr><td colspan="5">No Data Found</td></tr>';
}
$('tbody').html(html);
},
error: function(e) {
console.log(e);
}
})
}
$('#search').click(function(){
var query = $('#tags').val();
load_data(query);
});
});
</script>
and I have this error
"Uncaught TypeError: Cannot read property 'length' of null"
even if I put some words in search bar, I see there is 'null', not value.
I feel like I missed some important thing such as giving name to the data I want to send...
how can I give a name to the data I want to send?
and how can I connect the named data and function?
many thanks for your kindness in advance:-)
$("#sel_gram").change(function(){
var gramid = $(this).val();
$.ajax({
url: 'getBooth-details.php',
type: 'post',
data: {gram:gramid},
dataType: 'json',
success:function(response){
var len = response.length;
for( var i = 0; i<len; i++){
var id = response[i]['id'];
var name = response[i]['name'];
var booth_officer_name = response[i]['booth_officer_name'];
var booth_officer_contact = response[i]['booth_officer_contact'];
}
}
});
});
I want to add this to a table that I have designed below the select options.
I am getting all the data properly but I'm unable to use it in my table .
This is the table where i want to show the data.
<table class="table table-hover p-table">
<thead>
<tr>
<th>Booth Name</th>
<th>Booth Adhikari</th>
<th>Contact</th>
<th>Custom</th>
</tr>
</thead>
<tbody>
<tr>
<td class="p-name">
<h6 id="boothname">Name</h6>
</td>
<td class="p-team">
<h6 id="adhikariname"></h6>
</td>
<td>
<h6 id="adhikaricontact"></h6>
</td>
<td>
<i class="fa fa-folder"></i> View
<i class="fa fa-pencil"></i> Edit
<i class="fa fa-trash-o"></i> Delete
</td>
</tr>
</tbody>
</table>
This is where i want my data to be displayed.. where on click of view i want to take user to next page with id of the booth show that i can show further details
You can append every row using += in some variable and then use .html() to append same row inside your <tbody> .
Demo Code :
//your response
var response = [{
"id": "1",
"name": "Booth First",
"booth_officer_name": "First Adhikari",
"booth_officer_contact": "9827198271",
"gram_parshad_name": "Gram Officer One",
"gram_parshad_contact": "1231231231",
"gram_population": "10000",
"gram_house_count": "106",
"gram_voters_count": "8922",
"gram_polling_both_count": "20",
"zone_selected": "23",
"sector_selected": "14",
"panchayat_selected": "9",
"gram_selected": "6",
"zone_area": "dongargadh",
"zone_region": "rural"
}];
var len = response.length;
var data = "";
for (var i = 0; i < len; i++) {
//appeding each row inside <tr>
data += '<tr><td class="p-name"><h6 id="boothname">' + response[i]['name'] + '</h6> </td><td class="p-team"> <h6 id="adhikariname">' + response[i]['booth_officer_name'] + '</h6></td> <td><h6 id="adhikaricontact">' + response[i]['booth_officer_contact'] + '</h6></td><td><i class="fa fa-folder"></i> View <i class="fa fa-pencil"></i> Edit <i class="fa fa-trash-o"></i> Delete </td></tr>';
}
//appending data inside table <tbody>
$("#data").html(data)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-hover p-table" border="1">
<thead>
<tr>
<th>Booth Name</th>
<th>Booth Adhikari</th>
<th>Contact</th>
<th>Custom</th>
</tr>
</thead>
<tbody id="data">
<!--data will come here-->
</tbody>
</table>
I have some old code I am trying to poke through. This table is loaded via a Controller action returning a model, based off of a button click somewhere else in the page.
How can I find the number of rows in the table in a JS variable? I am terrible with JS. I have tried a few things and nothing has worked. Below is my code and also what I have tried to do to store the num of rows.
Table:
<hr />
<div class="row" id="ReceiptsMainDiv">
<div class="col-md-12" style="overflow-y:scroll">
<table class="table table-striped table-hover table-bordered" id="terminalReceipts">
<thead>
<tr>
<th>Terminal ID</th>
<th>Local Transaction Time</th>
<th>Amount</th>
<th>Receipt</th>
<td class="hidden"></td>
</tr>
</thead>
<tbody>
#foreach (var item in Model.TransactionsTests)
{
<tr id="#String.Concat("rowIndex", Model.TransactionsTests.IndexOf(item))">
<td>#item.TerminalID</td>
<td>#item.TransactionTime</td>
<td>#item.Amount</td>
#*<td>#Html.ActionLink("View Receipt", "ViewReceipt", new { id = item.Id }, new { #class = "btn btn-primary btn-sm" }) <br /></td>*#
<td class="transactionID hidden">#item.Id</td>
<td>
#if (item.ReceiptData == null)
{
<button class="btn btn-sm btn-primary viewReceipt" disabled>View Receipt</button>
}
else
{
<button class="btn btn-sm btn-primary viewReceipt" data-rowindex="#String.Concat("rowIndex", Model.TransactionsTests.IndexOf(item))">View Receipt</button>
}
</td>
</tr>
}
</tbody>
</table>
</div>
Here is what I have tried to do in JS:
var rowId = "#" + $(this).data("rowindex");
var row = $(rowId);
console.log(rowId);
console.log(row);
Results from the console.log don't appear to be accurate. Anything helps. Thanks
Probably you want the number of rows of your table.
// javascript
var rowsInTable = document.getElementById("terminalReceipts").getElementsByTagName("tr").length;
//jquery
var rowsInTable2 = $("#customers").children('tbody').children('tr').length;
//if you need to do something with the rows:
var rows = $("#customers").children('tbody').children('tr');
rows.each(function( index ) {
console.log( index + ": " + $( this ).text() );
});
you can also do that using jquery like this
var totalRowCount = $("#terminalReceipts tr").length; //this will give +1 row
var rowCount = $("#terminalReceipts td").closest("tr").length; //this will give actual row
I am trying to make items not in list but in div and if an item is clicked, the div will be in different colors and the item will be added into a column but if the item is clicked again, the item will changed to original color and in the column the item will be gone. I just can't think how to do it in angular way. I came to another option to be able to add in the column and to remove the item, there's a remove button but I am still curious how the select and deselect can be done.
This is what I have in my html (ignore my btn btn-primary classes I was using button to give it a try in the first place)
<!--Select App Features-->
<div class="panel-heading" ng-controller="FeaturesController as featuresCtrl">
<h1 class="text-center">App Features</h1>
<div class="text-center">
<div ng-repeat="app in featuresCtrl.apps" class="btn btn-primary platform-btn-style" ng-click="featuresCtrl.addPrices(app.name, app.price)">{{ app.name }}</div><br>
</div>
<div>
<table class="table table-striped table-hover">
<thead>
<tr>
<th>Device Added</th>
<th>Device Price</th>
<th></th>
</tr>
</thead>
<tr ng-repeat="appList in featuresCtrl.listAppPrices">
<td>{{ appList.name }}</td>
<td>{{ appList.price }}</td>
<td><button class="btn btn-default" ng-click="featuresCtrl.remove($index)">Remove</button></td>
</tr>
</table>
<div>Total : {{ featuresCtrl.totalAppPrice() }}</div>
</div>
</div><!-- end select app features / FeaturesController-->
My controller in js
//Controller for app features
app.controller("FeaturesController", function(){
this.apps = features;
this.listAppPrices = [];
// add name and price into the new array which is used to show in the table
this.addPrices = function(name, price){
//Checks if the exact name, price property exists in the array and return boolean
var found = this.listAppPrices.some(function (e){
console.log(e.name);
return ((e.name === name) && (e.price === price)) ;
});
//If found not true then push the new values into the array
if(!found){
this.listAppPrices.push({name: name, price: price});
}
};
// adds all the prices of the array which gives the total
this.totalAppPrice = function(){
var total = 0;
for(var i = 0; i < this.listAppPrices.length; i++){
total += this.listAppPrices[i].price;
}
return total;
};
// remove the whole object in the array when remove is clicked
this.remove = function(index) {
this.listAppPrices.splice(index, 1);
};
});
I kind of having the idea of how this can be done but I just can't think of the code to write it.
P.S. the codes are simple, I just learned it in code school and wanted to created something for fun to educate myself. Thanks in advance people
angular.module("stack", [])
.controller("FeaturesController", function($scope) {
// this.apps = features;
this.listAppPrices = [];
this.apps = [{ "name": "a1", "price": "12" }, { "name": "a2", "price": "13" }, { "name": "a3", "price": "14" }];
$scope.dummyArray = [];
var f = 0,
x = 0,
rem = false;
this.setSelected = function(app, index) {
console.log("app ", app);
//remove an item
if (app.selected) {
console.log(" list ", $scope.dummyArray);
$scope.dummyArray.forEach(function(e, ind) {
if (e.name === app.name) {
console.log(ind, " e ", e);
rem = true;
$scope.dummyArray.splice(ind, 1);
}
});
console.log("dumm ", $scope.dummyArray);
this.listAppPrices = $scope.dummyArray;
} else {
rem = false;
}
//used to select a div and change its colour
app.selected ? app.selected = false : app.selected = true;
//add an item
if (!rem) {
if ($scope.dummyArray.length) {
$scope.dummyArray.forEach(function(each) {
console.log("each ");
if (each.name !== app.name) {
console.log("inside if ");
f = 1;
}
});
} else {
console.log("inside else ");
$scope.dummyArray.push(app);
}
if (f === 1) {
f = 0;
console.log("push");
$scope.dummyArray.push(app);
}
console.log(" list--> ", $scope.dummyArray.length);
this.listAppPrices = $scope.dummyArray;
}
}
});
.selected {
background-color: gray;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.0/angular.min.js"></script>
<!DOCTYPE html>
<html ng-app="stack">
<head>
<title>stack</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="panel-heading" ng-controller="FeaturesController as featuresCtrl">
<h1 class="text-center x">App Features</h1>
<div class="text-center">
<div ng-repeat="app in featuresCtrl.apps track by $index" class="btn btn-primary platform-btn-style" ng-click="featuresCtrl.setSelected(app,$index)" ng-class="{selected: app.selected}">{{ app.name }}</div>
<!-- <div ng-if="(c%2===0)" ng-repeat="app in featuresCtrl.apps" class="btn btn-primary platform-btn-style" ng-click="featuresCtrl.setSelected(app)">{{ app.name }}</div> -->
<br>
</div>
<div>
<table class="table table-striped table-hover">
<thead>
<tr>
<th>Device Added</th>
<th>Device Price</th>
<th></th>
</tr>
</thead>
<tr ng-repeat="appList in featuresCtrl.listAppPrices">
<td>{{ appList.name }}</td>
<td>{{ appList.price }}</td>
<td>
<button class="btn btn-default" ng-click="featuresCtrl.remove($index)">Remove</button>
</td>
</tr>
</table>
<div>Total : {{ featuresCtrl.totalAppPrice() }}</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.0/angular.min.js"></script>
<script type="text/javascript" src="controller.js"></script>
</body>
</html>
I haven't added the functionality of remove button.I also haven't count the totalAppPrice. Otherwise your problem is solved :) .