Make a list with multiple pages in Jquery - javascript

I'm making a page with a list of products (which are loads using ajax) but i want to show only 6 products/page but i don't know how to do it and i don't find any examples that implements what i want. So for example if i have 20 products i want to show 6 in the first page, 6 in the second, .. etc to the last product in the last page (the page is always the same only the products change).
So in the end of the page i must have page 1-n
Can someone help me?
this is the js that load the products and show them one below the other:
$(document).ready(function () {
$.ajax({
type: "GET",
url: "json/projects.json",
dataType: "json",
success: function (data) {
showInfo(data);
},
});
});
function showInfo(data) {
var htmlString = "";
if (data.length == 0) {
htmlString =
"<span id = " +
"message>" +
"Non รจ stato trovato alcun progetto" +
"</span>";
$("#list").append(htmlString);
} else {
//altrimenti stampo data
for (i = 0; i < data.length; i++) {
//scorro tutto il mio file json
htmlString =
"<div class = " + "project id = " + data[i].id + ">" +
"<div class =" + "row-list>" +
"<div class = " + "title>" + data[i].title + "</div>" +
"<div class = " + "info>" + "<img src = " + "img/user.png>" + data[i].username + "</div>" +
"<div class = " + "info>" + "<img src = " + "img/budget.png>" + data[i].budget + "</div>" +
"<div class = " + "info>" + "<img src = " + "img/data.png>" + data[i].data + "</div>" +
"<div class = " + "flag>" + data[i].flag + "</div>" +
"</div>";
// collego al div #list le informazioni
$("#list").append(htmlString);
}
// aggiungo l'handler per visualizzare i dettagli quando un progetto viene cliccato
$(".project").click(function () {
window.location.href = "details.php?id=" + $(this).attr("id");
});
}
}

If the page doesn't change, you can stay on the same page while simply changing the products shown.
Here's a simplified version to demonstrate how this could work:
// create 20 product names
let products = [];
for (let i=1; i<=20; i++) {
products.push(`This is Product Name ${i}`);
}
let firstShown = 0;
const display = document.getElementById('display');
// display up to 6 products on page
function addToDisplay(first) {
display.innerHTML = '';
let last = Math.min(first+5, products.length-1);
for (let i = first; i <= last; i++) {
let li = document.createElement('li');
li.innerHTML = products[i];
display.appendChild(li);
}
}
function forward () {
display.innerHTML = '';
firstShown += 5;
addToDisplay(firstShown);
}
function back () {
display.innerHTML = '';
firstShown = Math.max(firstShown-5, 0);
addToDisplay(firstShown);
}
// show initial 6 producs
addToDisplay(firstShown);
<p>Display multiple products 6 at a time<br/>
<button type="button" onclick="back();">Back</button>
<button type="button" onclick="forward();">Forward</button>
</p>
<ul id="display"></ul>

Related

Why I need to clear local storage manually from console. Every time my site load

I made a shopping cart and make update cart function in JavaScript that working fine but when I navigate to other page my cart no automatically turn to (1 ) and an error rise in console like this:
Uncaught TypeError: Cannot set property 'innerHTML' of null
at updateCart ((index):447)
at (index):411
My javascript code is:
<script>
// Find out the cart items from localStorage
if (localStorage.getItem('cart') == null) {
var cart = {};
} else {
cart = JSON.parse(localStorage.getItem('cart'));
document.getElementById('cart').innerHTML = Object.keys(cart).length;
updateCart(cart);
}
// If the add to cart button is clicked, add/increment the item
$('.cart').click(function() {
var idstr = this.id.toString();
if (cart[idstr] != undefined) {
cart[idstr] = cart[idstr] + 1;
} else {
cart[idstr] = 1;
}
updateCart(cart);
});
//Add Popover to cart
$('#popcart').popover();
updatePopover(cart);
function updatePopover(cart)
{
console.log('We are inside updatePopover');
var popStr = "";
popStr = popStr + " <h5>Cart for your items in my shopping cart</h5><div class='mx-2 my-2'>";
var i = 1;
for (var item in cart){
popStr = popStr + "<b>" + i + "</b>. ";
popStr = popStr + document.getElementById('name' + item).innerHTML.slice(0,19) + "... Qty:
" + cart[item] + '<br>';
i = i+1;
}
popStr = popStr + "</div>"
console.log(popStr);
document.getElementById('popcart').setAttribute('data-content', popStr);
$('#popcart').popover('show');
}
function updateCart(cart) {
var sum = 0;
for (var item in cart) {
sum = sum + cart[item];
document.getElementById('div' + item).innerHTML = "<button id='minus" + item + "'
class='btn btn-dark minus'>-</button> <span id='val" + item + "''>" + cart[item] + "
</span> <button id='plus" + item + "' class='btn btn-dark plus'> + </button>";
}
localStorage.setItem('cart', JSON.stringify(cart));
document.getElementById('cart').innerHTML = sum;
console.log(cart);
updatePopover(cart);
}
// If plus or minus button is clicked, change the cart as well as the display value
$('.divpr').on("click", "button.minus", function() {
a = this.id.slice(7, );
cart['pr' + a] = cart['pr' + a] - 1;
cart['pr' + a] = Math.max(0, cart['pr' + a]);
document.getElementById('valpr' + a).innerHTML = cart['pr' + a];
updateCart(cart);
});
$('.divpr').on("click", "button.plus", function() {
a = this.id.slice(6, );
cart['pr' + a] = cart['pr' + a] + 1;
document.getElementById('valpr' + a).innerHTML = cart['pr' + a];
updateCart(cart);
});
</script>
After this error everytime I need to clear storage in console by typing localstorage.clear() and If I add some atom in cart and navigate to other category, my add to cart button not working.

display all json data with bootstrap card in a dynamic div using jquery

i'm still learning ajax,jquery and js here.. So in this problem i want to get the json data and display each of it into div id="card-body" dynamically one by one per ID, but it seems my code doesn't work because the result only show one div that have all the data inside of it. Are there any suggestion that can be added or changed within the code here?
<div class="container">
<div class="card">
<div class="card-header">
</div>
<div class="addDiv">
<div id="card-body">
</div>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
$(function () {
$.ajax({
url: "https://jsonplaceholder.typicode.com/posts",
success: function (result) {
$.each(result, function (index, item) {
var userId = item.userId;
var typeId = item.id;
var titleId = item.title;
var bodyId = item.body;
var $info = $("<p/>").html("user id: " + userId + "<br>"
+ "id: " + typeId + "<br>"
+ "title: " + titleId + "<br>"
+ "body: " + bodyId);
var html = '<div id="card-body>';
for (let i = 0; i < $(result).length; i++) {
const element = $(result)[i];
}
html += '</div>';
$(".addDiv").append(html);
$("div#card-body").append($info);
});
// console.log('success', result);
// console.log(result[0].body);
// console.log($(result).length);
}
});
});
</script>
for (let i = 0; i < $(result).length; i++) {
const element = $(result)[i];
}
what is here going to do?
or you mean this? --- Updated
$(function() {
$.ajax({
url: "https://jsonplaceholder.typicode.com/posts",
success: function(result) {
var container = $("div#list");
$.each(result, function (index, item) {
var userId = item.userId;
var id = "card-body-" + userId;
var el = $('div#' + id)
console.log(el)
var typeId = item.id;
var titleId = item.title;
var bodyId = item.body;
var $info = $('<div>').html(
"user id: " + userId + "<br>" +
"id: " + typeId + "<br>" +
"title: " + titleId + "<br>" +
"body: " + bodyId
);
if (!el.length) {
// not found, create new one
el = $('<div id="' + id + '">')
container.append(el)
}
el.append($info)
});
}
});
});

Show image from byte[] on CSHTML via javascript

I'm creating a timeline page with data from database, and I want to show a image from the object in the View.
The method Get it's working fine, when it returns the var imgSrc receives the data from the byte array converted to base64, but when I try to use the var in the it shows undefinied when I inspect the page.
Someone can give me a hand on how can I solve this?
$.getJSON("../ReportsAuditsTimeLine/GetAuditsResultbyAudit", { AuditID: ID },
function (data) {
var datafromaudit = '';
var div = document.createElement('div');
$('#timeLine').empty();
for (var i = 0; i < data.length; i++)
{
var base64 = "";
var imgSrc = "";
if (data[i].AUDIT_PICTURE != null)
{
//CHECK IMAGE
try {
base64 = Convert.ToBase64String(data[i].AUDIT_PICTURE);
imgSrc = String.Format("data:image/png;base64,{0}", base64);
console.log("Imagem:", imgSrc);
}
catch (Exception) {
}
//END IMAGE
}
if (data[i].AUDIT_ITEM_STATUS == "PASS") {
if (data[i].AUDIT_PICTURE != null) {
datafromaudit += '<li><i class="fa fa-camera bg-green"></i> ' +
'<div class="timeline-item">' +
'<span class="time">' +
'</span>' +
'<h3 class="timeline-header"><b>ID:' + data[i].ID + " - " + data[i].DESCRIPTION +
'</b></h3>' +
'<div class="timeline-body"> WEIGHT: <b>' + data[i].OD + '</b> STATUS: <b style=color:green;>' + data[i].AUDIT_ITEM_STATUS + '</b>' + '<img src="' + $.imgSrc + '"class="margin" ></img>' + ' </div>' +
'<div class="timeline-footer"/>'
'</div></li>'
}
else
{
datafromaudit += '<li><i class="fa fa-pencil-square-o bg-green"></i> ' +
'<div class="timeline-item">' +
'<span class="time">' +
'</span>' +
'<h3 class="timeline-header"><b>ID:' + data[i].ID + " - " + data[i].DESCRIPTION +
'</b></h3>' +
'<div class="timeline-body"> WEIGHT: <b>' + data[i].OD + '</b> STATUS: <b style=color:green;>' + data[i].AUDIT_ITEM_STATUS + '</b>' + ' </div>' +
'<div class="timeline-footer"/>'
'</div></li>'
}
}
}
CONTROLLER
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult GetAuditsResultbyAudit(string AuditID)
{
var viewModel = new ReportsAuditTimeLineViewModel();
int auditID = Int32.Parse(AuditID);
var auditResults = viewModel.GetAuditsResultbyAudit(auditID);
return Json(auditResults, JsonRequestBehavior.AllowGet);
}
VIEWMODEL
public List<AuditsResultData> GetAuditsResultbyAudit(int AuditID)
{
var list = new List<AuditsResultData>();
var context = new OnlineAuditsEntities();
using (context)
{
var query = from audits in context.tb_Audits
join i in context.tb_AuditItem on audits.AUDIT_ITEM_ID equals i.ID
join a in context.tb_Audit on audits.AUDIT_ID equals a.ID
join s in context.tb_Audit_ItemStatus on audits.STATUS_ID equals s.ID
where audits.AUDIT_ID == AuditID
select new { audits, i,a,s};
foreach (var s in query)
{
var Photo = (from pic in context.tb_AuditPictures
where pic.AUDIT_ID == s.audits.ID
select pic.PICTURE).FirstOrDefault();
if (Photo!=null)
{
list.Add(new AuditsResultData
{
ID = s.audits.ID,
AUDIT_ITEM_ID = s.audits.AUDIT_ITEM_ID,
DESCRIPTION = s.i.SUBCATEGORY_DESCRIPTION,
HASFIND = s.i.HAS_FINDING ?? false,
FINDS = s.audits.FINDINGS ?? 0,
STATUS_ID = s.audits.STATUS_ID,
AUDIT_ITEM_STATUS = s.s.STATUS_DESCRIPTION,
OD = s.audits.OD ?? 0,
COMMENTS = s.audits.COMMENTS,
SCANS = s.audits.SCANNED_CODE,
AUDIT_ID = s.audits.AUDIT_ID,
AUDIT_PICTURE = Photo
});
}
}
}
return list;
}
You should pass picture to view as Base64String from controller. Then convert it to picture like:
var picture = "data:image/jpg;base64," + data.base64image;

Getting position of specifing item from localStorage

I'm working on a simple aplication based on localStorage and I have a problem with removing an item.
So, I'm adding new items to LS and display them as divs in for loop.
I created an easy "X" button on every card and here is a thing. How can I get an ID/position of this specific card after clicking "X" and pass it to remove function?
I'll present you my code:
// Display activities
var fetchActivities = function() {
var activities = JSON.parse(localStorage.getItem("activitie"));
const actCountContainer = document.getElementById("actCountContainer");
actCountContainer.innerHTML = "";
actCountContainer.innerHTML += "<div class='col-md-12'>" +
"<p>Your activities ("+activities.length+")";
var actCardContainer = document.getElementById("actCardContainer");
actCardContainer.innerHTML = "";
for (let i = 0; i < activities.length; i++) {
actCardContainer.innerHTML += '<div class="col-md-4">'+
'<div class="card">' +
'<div class="card-block">' +
'<div id="remove" class="remove">X</div>' +
'<h4 class="card-title">'+ activities[i].name + '</h4>' +
'<ul class="card-text">' +
'<li>Total time spent: 2h 25min 34sec</li>' +
'</ul>' +
'Go to this activity' +
'</div>' +
'</div>' +
'</div>'
}
const removeButton = document.getElementById("remove");
if (removeButton) {
removeButton.addEventListener("click", removeActivity);
};
};
// Add activity function
var addActivity = function() {
const actInput = document.getElementById("activityInput").value;
// Main activity object
var activity = {
name: actInput
};
if (localStorage.getItem("activitie") == null) {
var activities = [];
activities.push(activity);
localStorage.setItem("activitie", JSON.stringify(activities));
} else {
var activities = JSON.parse(localStorage.getItem("activitie"));
activities.push(activity);
localStorage.setItem("activitie", JSON.stringify(activities));
}
fetchActivities();
};
// Remove activity function
var removeActivity = function() {
};
const addButton = document.getElementById("addBtn");
addButton.addEventListener("click", addActivity);
I'd be very grateful if you can give me an idea how can I handle this remove function.
I would rewrite fetchActivities as follows
var fetchActivities = function() {
var activities = JSON.parse(localStorage.getItem("activitie"));
const actCountContainer = document.getElementById("actCountContainer");
actCountContainer.innerHTML = "";
actCountContainer.innerHTML += "<div class='col-md-12'>" +
"<p>Your activities ("+activities.length+")";
const actCardContainer = document.getElementById("actCardContainer");
actCardContainer.innerHTML = "";
let items = "";
for (let i = 0; i < activities.length; i++) {
itemsHTML += '<div class="col-md-4">'+
'<div class="card" data-id="' + activities[i].id + '">' +
'<div class="card-block">' +
'<div class="remove" data-id="' + activities[i].id + '">X</div>' +
'<h4 class="card-title">'+ activities[i].name + '</h4>' +
'<ul class="card-text">' +
'<li>Total time spent: 2h 25min 34sec</li>' +
'</ul>' +
'Go to this activity' +
'</div>' +
'</div>' +
'</div>'
}
actCardContainer.innerHTML = items;
// ... for attach event read on
};
Notes:
Do not set the same id if an element appears many times
Set innerHTML once not for each loop iteration
Set unique id for every item (you could generate random numbers for example)
To attach events you would need to do it as follows (taken from question ):
var removeLink = document.querySelectorAll('.remove');
Then you would loop:
for (var i = 0; i < deleteLink.length; i++) {
removeLink[i].addEventListener('click', function(event) {
var acrtivityId = event.currentTarget.getAttribute('data-id');
removeActivity(acrtivityId);
// Use
});
}
Now for the removal you can find current activity in the activity array and remove it. Use find and then splice for example. And save the change array to local storage. On creation assign an id.

Hiding elements with JS

UPDATE:
I changed my script to this and it works. Way simpler and it works.
function myFunction(valor) {
var elementos = document.getElementsByClassName("inner");
var i;
for (i = 1; i < elementos.length+1; i++) {
document.getElementById("age"+i).style.visibility = "hidden";
}
document.getElementById("age"+valor).style.visibility = "visible";
}
I have this script:
function myFunction(valor) {
alert("Has seleccionado " + valor);
var elementos = document.getElementsByClassName("inner");
//alert ("Tienes " + elementos.length + " elementos.");
var i;
for (i = 1; i < elementos.length + 1; i++) {
var sty = document.getElementById("age" + i);
//alert("age"+i);
if (getComputedStyle(sty).getPropertyValue("visibility") == "hidden") {
document.getElementById("age" + valor).style.visibility = "visible";
} else {
document.getElementById("age" + i).style.visibility = "hidden";
}
}
}
That I control with a slider control. What I'm doing is hiding or showing some divs with depending of what I choose from the slider.
This is how I paint my data before trying to hide or shsow elements with the slider:
$(window).load(function() {
$.getJSON('http://xxxxx/xxxxx.json', function(data) {
var output = "<ul class='lista'><div class='outer'>";
for (var i in data.lbclassic) {
output += "<div style='visibility:hidden;' class='inner'id=" + "age" + data.lbclassic[i].ageinweeks + ">" + "<p>" + data.lbclassic[i].ageinweeks + "--" + data.lbclassic[i].cumul + "--" + data.lbclassic[i].perhh + "--" + data.lbclassic[i].perhd + "--" + data.lbclassic[i].eggweightinweek + "--" + data.lbclassic[i].eggmasscumul1 + "--" + data.lbclassic[i].eggmassinweek + "--" + data.lbclassic[i].eggmasscumul + "</p></div>";
}
output += "</div></ul>";
document.getElementById("placeholder").innerHTML = output;
});
});
This works great until one point - once I get to the last element (90 in this case), it won't show up.
Isn't it more easy to use the css "display:none;" feature for hidding your element.
.yourclass{
display:none;
}
just edit the class with js
Link to CSS
function myFunction(valor) {
var elementos = document.getElementsByClassName("inner");
var i;
for (i = 1; i < elementos.length+1; i++) {
document.getElementById("age"+i).style.visibility = "hidden";
}
document.getElementById("age"+valor).style.visibility = "visible";
}

Categories

Resources