Sort jQuery Ajax Json forEach data by date - javascript

I'm getting my data from a JSON file. But my code read and append it as it's written in the file I'd like to sort the data by date.
I tryed this : but doesn't work =/
$('.1article').sort(function (a, b) {
var contentA =parseInt( $(a).attr('data-date'));
var contentB =parseInt( $(b).attr('data-date'));
return (contentA < contentB) ? -1 : (contentA > contentB) ? 1 : 0;
})
My Ajax code
$(document).ready(function() {
function imgError(image) {
image.onerror = "";
image.src = "img/S0-voiture-de-l-annee-2017-les-sept-finalistes-nos-pronostics-391613.jpg";
return true;
}
$.ajax({
type: "GET",
url: 'http://s604712774.onlinehome.fr/videdressing/text.json',
dataType: 'json',
success: function(data) {
data.forEach(function(post) {
var fds = new Date(post.date) ;
var datetimeposted = new Date(post.date);
var datetime = datetimeposted.getDate() + "/" + (datetimeposted.getMonth()+1) + "/" + datetimeposted.getFullYear();
var currentdate = new Date();
var now = new Date(currentdate.getFullYear() + ", " + ( '0' +(currentdate.getMonth()+1)).slice( -2 ) + ", " + ( '0' +currentdate.getDate()));
var result = (now - fds) ;
var days = result / 1000 / 60 / 60 / 24 ;
if ("14" < days) {
$(".id" + post.id).css('display','none');
};
$( '.articles' ).prepend( ' <div class="1article col s12 m6 l4 id' + post.id + '" data-date="' + fds +'"> <div class="card"> <div class="card-content"> <span class="titlevente activator grey-text text-darken-4 titlevente">' + post.title +'</span><br><span class="titlevente activator grey-text text-darken-4 titlevente" style="font-size:10px !important;">' + post.category +' | ' + datetime +'</span> </div><div class="card-image waves-effect waves-block waves-light"> <img class="activator" src="img/S0-voiture-de-l-annee-2017-les-sept-finalistes-nos-pronostics-391613.jpg"> </div><div class="card-content"> <span class="metadesc activator grey-text text-darken-4">' + post.ville +' | ' + post.prix +'€<i class="material-icons right">more_vert</i></span> </div><div class="card-reveal"> <span class="card-title grey-text text-darken-4">' + post.title +'<i class="material-icons right">close</i></span> <p>' + post.decription +'</p><div class="incarddata"> <i id="delete" class="material-icons h32"></i> <i class="material-icons h32">share</i> <i class="material-icons h32"></i> <i class="material-icons h32"></i> </div></div></div></div>' );
});
}
});
});
You can look it up here -> https://jsfiddle.net/ds77bmu9/1/

I edited your fiddle, you had to sort the array before iterating through it. Also, your sorting function was not right (In javascript you can simply subtract dates with - ):
success: function(data) {
data.sort(function(a, b) {
return new Date(b.date) - new Date(a.date);
})
foreach(data : ...)
}
here is your fiddle fixed. https://jsfiddle.net/ds77bmu9/3/

Related

Run a javascript from a html table cell

I am using asp.net core 5 and I have the following cell in a table -
<td id="actionId" class="text-left">
<input hidden id="renewalDueId" type="hidden" asp-for="#clinic.RenewalDue" class="form-control" />
<input hidden id="nextRenewalDueAtId" asp-for="#clinic.VaccClinic.NextRenewalDueAt" class="form-control" />
<input hidden id="dedesignatedDateId" asp-for="#clinic.VaccClinic.DedesignationDate" class="form-control" />
<div id="designationPlaceHolderHere"></div>
Training Status: <br /><br />
Annual Returns Figures:
#if (clinic.NumberOfVaccinations.HasValue)
{
<label>#clinic.NumberOfVaccinations.Value.ToString()</label>
if (clinic.NumberOfAdverseEvents.HasValue)
{
<label> - #clinic.NumberOfAdverseEvents.Value.ToString()</label>
}
else
{
<label> - 0</label>
}
}
else
{
<label style="background-color:red">
Not Submitted
</label>
}
</td>
I am trying to call a javascript function and add html at designationplaceholder for each record in the table.
I have tried -
$('tr').each(function (i, item) {
var html = DesignationStatus($('#dedesignatedDateId').val(), $('#renewalDueId').val(), $('#nextRenewalDueAtId').val(), #(ViewBag.NumberOfDays));
$('#designationPlaceHolderHere').html(html);
});
Doesn't work properly.
I want to call the function, for each record, passing the appropriate values for each record.
Any ideas?
Thanks
[UPDATE]
This is the function I call -
function DesignationStatus(dedesignatedDate, renewalDue, nextRenewalDue, numberOfDays) {
var isRenewalDue = (renewalDue === 'true')
//Get today's date
var d = new Date();
var month = d.getMonth() + 1;
var day = d.getDate();
var todaysDate = d.getFullYear() + '/' +
(month < 10 ? '0' : '') + month + '/' +
(day < 10 ? '0' : '') + day;
//Create next renewal due date display value.
var reDate = new Date(nextRenewalDue);
var reDay = reDate.getDate();
var reMonth = reDate.getMonth() + 1;
var displayRenewalDate = (reDay < 10 ? '0' : '') + reDay + '/' + (reMonth < 10 ? '0' : '') + reMonth + '/' + reDate.getFullYear()
//Create de-designation date display value.
var deDate = new Date(dedesignatedDate);
var deDay = deDate.getDate();
var deMonth = deDate.getMonth() + 1;
var displayDedesignationDate = (deDay < 10 ? '0' : '') + deDay + '/' + (deMonth < 10 ? '0' : '') + deMonth + '/' + deDate.getFullYear()
//Calculate what one day is
var oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
//Parse the number off days passed in
var numOfDays = parseInt(numberOfDays);
//If no number has been passed in set to default of 90.
if (isNaN(numberOfDays)) {
numOfDays = 90;
}
//Start html string
var html = '<div>'
html += ' <label>Designation status:</label>'
html += ' </div>'
html += ' <div>'
//Get rest of html dependant on due date etc.
if (dedesignatedDate != null && dedesignatedDate != "") {
html += ' <div class="alert alert-danger" role="alert" style="text-align : center; height : 47.5px;">'
html += ' <label>De-designated on</label>' + ' ' + displayDedesignationDate
}
else {
if (nextRenewalDue != null && nextRenewalDue != "") {
var today = new Date();
var renewal = new Date();
today = Date.parse(todaysDate);
renewal = Date.parse(nextRenewalDue);
if (renewal > today) {
if (!isRenewalDue) {
html += ' <div class="alert alert-success" role="alert" style="text-align : center; height : 47.5px;">'
html += ' <label>Active</label>'
}
else {
html += ' <div class="alert alert-warning" role="alert" style="text-align : center; height : 47.5px;">'
html += ' <label>Due to renew - renew before </label>' + ' ' + displayRenewalDate
}
}
else if (renewal < today) {
//Work out the number of days between renewal and today's date
var diffDays = Math.round(Math.abs(((new Date(today).getTime()) - (new Date(renewal).getTime())) / (oneDay)));
if (diffDays < numOfDays) {
html += ' <div class="alert alert-danger" role="alert" style="text-align : center; height : 47.5px;">'
html += ' <label>Inactive - lapsed on </label>' + ' ' + displayRenewalDate;
}
else {
html += ' <div class="alert alert-danger" role="alert" style="text-align : center; height : 47.5px;">'
html += ' <label>Inactive</label>'
}
}
}
}
//Finish off the html string
html += ' </div>'
html += ' </div>'
html += '</div>'
//return html strin
return html
}
<td id="actionId" class="text-left" onclick="DesignationStatus('#clinic.VaccClinic.DedesignationDate','#clinic.RenewalDue','#clinic.VaccClinic.NextRenewalDueAt','#ViewBag.NumberOfDays')">
<input hidden id="renewalDueId" type="hidden" asp-for="#clinic.RenewalDue" class="form-control" />
<input hidden id="nextRenewalDueAtId" asp-for="#clinic.VaccClinic.NextRenewalDueAt" class="form-control" />
<input hidden id="dedesignatedDateId" asp-for="#clinic.VaccClinic.DedesignationDate" class="form-control" />
<div id="designationPlaceHolderHere"></div>
Training Status: <br /><br />
Annual Returns Figures:
#if (clinic.NumberOfVaccinations.HasValue)
{
<label>#clinic.NumberOfVaccinations.Value.ToString()</label>
if (clinic.NumberOfAdverseEvents.HasValue)
{
<label> - #clinic.NumberOfAdverseEvents.Value.ToString()</label>
}
else
{
<label> - 0</label>
}
}
else
{
<label style="background-color:red">
Not Submitted
</label>
}
This should call your javascript function. Also never use the same id="dedesignatedDateID".

Data Hash attribute on Owl Carousel not working on dynamic generated carousel

Right now I am developing the front end of a web application written in Jquery(JS). I am aiming to use Owl Carousel to load dynamic data from a JSON.
I already make it work to load all the items from the JSON and create the carousel dynamically on a "for" loop. Everything is working as expected, although my problem is to get de "data-hash" attribute on the url everytime I switch slider, I know that Owl Carousel has this function built-in on the plugin, but actually is not working on my code. Any Idea?
This is my code
for (var key in data_allapprovedjson) {
if (data_allapprovedjson.hasOwnProperty(key)) {
for (var key2 in data_allapprovedjson[key]) {
console.log(data_allapprovedjson[key]);
var itemid = data_allapprovedjson[key][key2].itemid;
var itemname = data_allapprovedjson[key][key2].itemname;
var itemdescription = data_allapprovedjson[key][key2].description;
var itemsellerid = data_allapprovedjson[key][key2].sellerid;
var itemsellername = data_allapprovedjson[key][key2].sellername;
var itemprice = data_allapprovedjson[key][key2].price;
var itemgender = data_allapprovedjson[key][key2].gender;
var itemfashion = data_allapprovedjson[key][key2].fashion;
var itemposeanimations = data_allapprovedjson[key][key2].poseanimations;
var itemhomegarden = data_allapprovedjson[key][key2].homegarden;
var itembodyshop = data_allapprovedjson[key][key2].bodyshop;
var itemmiscellaneous = data_allapprovedjson[key][key2].miscellaneous;
var itemmodify = data_allapprovedjson[key][key2].modify;
var itemcopy = data_allapprovedjson[key][key2].copy;
var itemtransfer = data_allapprovedjson[key][key2].transfer;
var itemexpire = data_allapprovedjson[key][key2].expiresin;
var itemimage1 = data_allapprovedjson[key][key2].image1;
var itemimage2 = data_allapprovedjson[key][key2].image2;
var itemimage3 = data_allapprovedjson[key][key2].image3;
var itemvideo = data_allapprovedjson[key][key2].video;
//Variaveis Nome de elementos Estáticos no Layout
var descricao = "Product Description";
var variation = "Variation of this product";
var permissao = "Permissions of this product";
var linen = "$L ";
var expiracao = "Expires in ";
var sold = "Sold by: ";
var vendorStore = "Vendor Store";
var categories = "Categories";
function init_carousel() {
var owl = $('.owl-carousel');
owl.owlCarousel({
items: 1,
loop: false,
center: true,
nav: true,
URLhashListener: true,
autoplayHoverPause: true,
startPosition: 'URLHash'
});
owl.owlCarousel();
// Go to the next item
$('#next').click(function() {
owl.trigger('next.owl.carousel');
})
// Go to the previous item
$('#prev').click(function() {
// With optional speed parameter
// Parameters has to be in square bracket '[]'
owl.trigger('prev.owl.carousel', [300]);
})
}
$('.owl-stage').append('<div id="" class="container-fluid min-vh-100 pb-5 padding-top-2 owl-item" data-hash="' + itemid + '"><div class="row"><div class="col-6 d-flex"><div id="carousel-thumb" class="carousel slide carousel-fade carousel-thumbnails" data-ride="carousel"><div class="carousel-inner" role="listbox"><div class="carousel-item active"><img class="d-block w-100" src="https://mdbootstrap.com/img/Photos/Slides/img%20(88).jpg" alt="First slide"></div><div class="carousel-item"><a id="lightbox" href="https://mdbootstrap.com/img/Photos/Slides/img%20(121).jpg"><img class="d-block w-100" src="https://mdbootstrap.com/img/Photos/Slides/img%20(121).jpg" alt="Second slide"><i class="fas fa-search-plus zoom-icon"></i></a></div><div class="carousel-item"><a id="lightbox" href="https://mdbootstrap.com/img/Photos/Slides/img%20(31).jpg"><img class="d-block w-100" src="https://mdbootstrap.com/img/Photos/Slides/img%20(31).jpg" alt="Third slide"><i class="fas fa-search-plus zoom-icon"></i></a></div><div class="carousel-item"><a id="lightbox" href="https://mdbootstrap.com/img/Photos/Slides/img%20(31).jpg"><img class="d-block w-100" src="https://mdbootstrap.com/img/Photos/Slides/img%20(31).jpg" alt="Third slide"><i class="fas fa-search-plus zoom-icon"></i></a></div></div><a class="carousel-control-prev" href="#carousel-thumb" role="button" data-slide="prev"><span class="carousel-control-prev-icon" aria-hidden="true"></span><span class="sr-only">Previous</span></a><a class="carousel-control-next" href="#carousel-thumb" role="button" data-slide="next"><span class="carousel-control-next-icon" aria-hidden="true"></span><span class="sr-only">Next</span></a><h4 class="pt-3 title-variations">Product Images</h4><ol class="carousel-indicators"><li data-target="#carousel-thumb" data-slide-to="0" class="active"> <img class="d-block w-100" src="https://mdbootstrap.com/img/Photos/Others/Carousel-thumbs/img%20(88).jpg" class="img-fluid"></li><li data-target="#carousel-thumb" data-slide-to="1"><img class="d-block w-100" src="https://mdbootstrap.com/img/Photos/Others/Carousel-thumbs/img%20(121).jpg" class="img-fluid"></li><li data-target="#carousel-thumb" data-slide-to="2"><img class="d-block w-100" src="https://mdbootstrap.com/img/Photos/Others/Carousel-thumbs/img%20(31).jpg" class="img-fluid"></li><li data-target="#carousel-thumb" data-slide-to="3"><img class="d-block w-100" src="https://mdbootstrap.com/img/Photos/Others/Carousel-thumbs/img%20(31).jpg" class="img-fluid"></li></ol></div></div><div class="col-6"><h1 class="product-title">' + itemname + '</h1><h1 class="product-price">' + linen + itemprice + ' <i class="far fa-calendar-alt"></i>' + expiracao + itemexpire + '</h1><ul class="vendor"><li><img src="https://mdbootstrap.com/img/Photos/Slides/img%20(121).jpg" style="object-fit:cover;border-radius: 100%;margin-top: 15px; margin-right: 10px;" height="40" width="40">vendorStore</li><li class="sold-by">' + sold + itemsellername + '</li></ul><div class="padding-top-30"></div><div class="padding-box"><h3 class="product-description-title pt-3">' + descricao + '</h3><p class="product-description-text">' + itemdescription + '</p><div class="padding-box"><form><div class="form-group"><label class="select-text" for="exampleFormControlSelect1">' + variation + '</label><select class="form-control" id="exampleFormControlSelect1"><option></option><option></option><option></option><option></option><option></option></select></div></form></div><!--/Select Variation--><!--Product Category--><div class="padding-box"><h3 class="product-description-title">' + categories + '</h3><ul class="categories-list"><li>' + itemfashion + '</li><li>' + itemposeanimations + '</li><li>' + itemhomegarden + '</li><li>' + itemmiscellaneous + '</li><li>' + itembodyshop + '</li></ul></div><div class="padding-box"><h3 class="product-description-title">' + permissao + '</h3><ul class="permissions-list"><li><i class="fas fa-edit"></i>' + itemmodify + '</li><li><i class="fas fa-exchange-alt"></i>' + itemtransfer + '</li><li><i class="far fa-copy"></i> ' + itemcopy + '</li></ul></div></div></div></div></div> ');
}
}
}
jQuery(document).ready(function() {
init_carousel();
});
The Variable that is populating the "Data Hash" attribute is "itemid", but nothing is happening on the url, when I inspect the whole Owl Carousel, the value of that looped variable is printed on the "data-hash" as it should be but not sending it to the url when I drag or change slider via BTN like on this example: https://owlcarousel2.github.io/OwlCarousel2/demos/urlhashnav.html
I already tried the following:
owl.on('changed.owl.carousel', function() {
window.location.hash = itemid;
});
This Worked but it only returned the last value of the variable itemid on every slide.
Note: I am not an expert on JS but I understand the language and logic, but I am around this one for days and any help is welcomed. Thank you!

jQuery code not working when migrating from SP2013 to SP2019

I have a code that is working perfectly on SP2013 as a page layout. What the code does is to load items from a list, it show the first 4 items and then when you clicked the load more button it loads 4 more items until it reaches the total number of items; when you click the reset button it goes back to 4 items. When I migrated the code to SP2019 and converted it into a web part the items don't show, the are in the DOM but not showing. I have a class of .content set to display: none; when I remove it all the items show but this is not the expected result; I expect just the 4 first items to show by default and when the load more is clicked to show 4 more. What is strange is that it is working correctly on SP2013 but not in 2019, and the console does not show any errors.
<div class="content col-md-6"></div>
.content {
display: none;
}
$(document).ready(function() {
$(".content").slice(0, 4).show();
$(".resetBtn").hide();
var items = $(".content").length;
var shown;
$(".loadMore").click(function() {
$(".resetBtn").show();
shown = $(".content:visible").length + 4;
if (shown < items) {
$(".content:lt(" + shown + ")").show(300);
} else {
$(".content:lt(" + items + ")").show(300);
$(".loadMore").hide();
}
});
$(".resetBtn").click(function() {
var end = $(".content").length;
console.log(end);
$(".content").slice(4, end).hide(300);
$(".loadMore").show();
$(".resetBtn").hide();
});
});
I just had to move the script into the ajax call
var buildManagersCards = function(items) {
var managersContent = $("#managersContent");
for (let i = 0; i < items.length; i++) {
//build cards
var managersCards =
'<div class="content col-md-6"><div class="single-news mb-4"><div class="row"><div class="col-md-3"><div class="view overlay rounded z-depth-1 mb-4"><img class="img-fluid" src="' + items[i].Image.Url +'" alt="' + items[i].Title + '" /><a><div class="mask rgba-white-slight waves-effect waves-light"></div></a></div></div><div class="col-md-9"><p class="font-weight-bold dark-grey-text">' + items[i].Title +
'</p><div class="d-flex justify-content-between"><div class="col-11 pl-0 mb-3 managerDescription"><div>' + items[i].Description+'</div><div class="managerDate"><small>' + items[i].date+'</small></div><a data-toggle="modal" data-target=#basicExample'+items[i].ID+'><span class="modalButton" >Read More</span></a></div><a data-toggle="modal" data-target=#basicExample'+items[i].ID+'><i class="fas fa-angle-double-right modalArrow"></i></a></div></div></div></div></div>';
managersContent.prepend(managersCards);
}
};
var buildModal = function(items) {
var modalContent = $('#modalContent');
for (let i = 0; i < items.length; i++) {
var modalContentCard = '<div class="modal fade" id=basicExample'+ items[i].ID+' tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"><div class="modal-dialog modal-lg" role="document"><div class="modal-content"><div class="modal-header"><h5 class="modal-title" id="exampleModalLabel"><strong>' + (items[i].Title || ' ') +
'</strong></h5><button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button></div><div class="modal-body"><h5>Personal:</h5><p><strong>A dream I have is to:</strong> '+ (items[i].Dream || ' ') +'</p><p><strong>You would be surprised to learn that I:</strong>'+ (items[i].Learn || ' ') +'</p><p><strong>My motto is:</strong>'+( items[i].Motto || ' ') +
'</p><p><strong>The mission of our agency is:</strong>'+ (items[i].Mission || ' ') +'</p><hr><h5>Our current priorities are:</h5><p>'+ (items[i].Priorities || ' ') +'</p><h5>Our biggest accomplishments in the past year include:</h5><p>'+ (items[i].Accomplishments || ' ') +'</p><div class="agency"><h5>One thing you did not know about our agency is:</h5><p>'+ (items[i].Agency || ' ')+'</p></div><div class="mt-3 mb-3">'+ (items[i].Website || ' ') +'</div><div class="modal-footer"><button type="button" class="btn btn-primary" data-dismiss="modal">Close</button></div></div></div></div></div>';
modalContent.prepend(modalContentCard);
}
};
//ajax call
var url1 =
"/ManagersMoments/_api/web/lists/GetByTitle('managersMoments')/items";
var handle_ajax = function(url) {
$.ajax({
url: url,
method: "GET",
headers: {
Accept: "application/json; odata=verbose"
},
success: function(data) {
var items = data.d.results;
console.log(items);
buildManagersCards(items);
buildModal(items);
$(".content").slice(0, 4).show();
$(".resetBtn").hide();
var items = $(".content").length;
var shown;
$(".loadMore").click(function() {
$(".resetBtn").show();
shown = $(".content:visible").length + 4;
if (shown < items) {
$(".content:lt(" + shown + ")").show(300);
} else {
$(".content:lt(" + items + ")").show(300);
$(".loadMore").hide();
}
});
$(".resetBtn").click(function() {
var end = $(".content").length;
console.log(end);
$(".content").slice(4, end).hide(300);
$(".loadMore").show();
$(".resetBtn").hide();
});
},
error: function(data) {
console.log("Error: " + data);
}
});
};
handle_ajax(url1);

How to load data from two separate XML files?

I'm trying to load XML data from two separate files. On page load, I want to show data of one file by default. There would be a button on the page to display data from next file.
After load XML files, I need to combine all popup boxes with looping. But my code does not support to loop that popups. how can I implement the below code? Please help.
Here is my code.
$(document).ready(function(){
$.ajax({
type:"GET",
url:"contact.xml",
dataType:"xml",
success:xmlParser2
});
});
function xmlParser2(xml){
var items = $(xml).children().children();
items.sort(function() { return 0.5 - Math.random() });
xml = $(xml).children();
let i = 0;
let total = $(xml).children().length;
items.each(function (idx,index,item) {
let expireArray = $(this).attr('expires').split('/');
const expireDate = `${expireArray[2]}${expireArray[1]}${expireArray[0]}`;
const now = new Date(),
nowDate = `${now.getFullYear()}${(now.getMonth()+1) <10 ? '0'+(now.getMonth()+1): (now.getMonth()+1)}${now.getDate()}`;
if (nowDate > expireDate) {
return;
}
let tag = $(this).prop("tagName")+index;
let nextIdx = idx + 1;
let prevIdx = idx - 1;
//to make cyclic
nextIdx = nextIdx == total ? 0 : nextIdx;
prevIdx = prevIdx == -1 ? (total -1) : prevIdx;
let image = '<img style="background-image:url(' + $(this).find("image").text() + ')"' + '" />';
let image2 = '<div><img src="' + $(this).find("image").text() + '" width="100%" alt="' + '" />' + '</div>';
let head = '<div>' + $(this).find("head").text() + '</div>';
let html = `<div class="col-sm-4 random" id="random">
<div class="thumbnail randomdiv3" id="border" >
<a href="#${tag + idx}" id="openModalBtn">
<div>${image}</div>
<h5>${head}</h5>
</a>
</div>
</div>`;
let popup = `<div id="${tag + idx}" class="overlay">
<div class="popup">
‹
›
<h6>${head}</h6>
<a class="close" href="#">×</a>
<div>${image2}</div>
</div>
</div>`;
i++;
if(i <= 3) {
$("#xmldata").append(html);
$("#image_boxes").append(html);
}
else{
$("#rest_image_boxes").append(html);
}
$("#popup").append(popup);
});
var hash = window.location.hash;
if(hash != ""){
$("a[href='"+hash+"']").find("h5").click();
}
$("a[id='openModalBtn']").click(function(){
window.location.hash = $(this).attr("href");
});
}
function xmlParser3(xml){
var items = $(xml).children().children();
items.sort(function() { return 0.5 - Math.random() });
xml = $(xml).children();
let i = 0;
let total = $(xml).children().length;
items.each(function (idx,index,item) {
let expireArray = $(this).attr('expires').split('/');
const expireDate = `${expireArray[2]}${expireArray[1]}${expireArray[0]}`;
const now = new Date(),
nowDate = `${now.getFullYear()}${(now.getMonth()+1) <10 ? '0'+(now.getMonth()+1): (now.getMonth()+1)}${now.getDate()}`;
if (nowDate > expireDate) {
return;
}
let tag = $(this).prop("tagName")+index;
let nextIdx = idx + 1;
let prevIdx = idx - 1;
//to make cyclic
nextIdx = nextIdx == total ? 0 : nextIdx;
prevIdx = prevIdx == -1 ? (total -1) : prevIdx;
let image = '<img style="background-image:url(' + $(this).find("image").text() + ')"' + '" />';
let image2 = '<div><img src="' + $(this).find("image").text() + '" width="100%" alt="' + '" />' + '</div>';
let head = '<div>' + $(this).find("head").text() + '</div>';
let html = `<div class="col-sm-4 random" id="random">
<div class="thumbnail randomdiv3" id="border" >
<a href="#${tag + idx}" id="openModalBtn">
<div>${image}</div>
<h5>${head}</h5>
</a>
</div>
</div>`;
let popup = `<div id="${tag + idx}" class="overlay">
<div class="popup">
‹
›
<h6>${head}</h6>
<a class="close" href="#">×</a>
<div>${image2}</div>
</div>
</div>`;
$("#rest_image_boxes").append(html);
$("#popup").append(popup);
});
var hash = window.location.hash;
if(hash != ""){
$("a[href='"+hash+"']").find("h5").click();
}
$("a[id='openModalBtn']").click(function(){
window.location.hash = $(this).attr("href");
});
}
$('#myButton1').click(function(e){
e.preventDefault();
$.ajax({
type:"GET",
url:"data.xml",
dataType:"xml",
success:xmlParser3
});
});
<div class="row" id="xmldata"></div>
<section>
<div class="container">
<input type="button" value="View All" id="myButton1" class="reveal" style="float: right;" onclick="toggler('toggle_container');">
<div id="toggle_container" class='hide'>
<div class="block">
<div class="row" id="rest_image_boxes"></div>
</div>
</div>
</div>
</section>
<section id="popup"></section>
Plunker

How to render a List Element using VueJs from a json data

I have a javascript code which renders <ol><li></li></ol> , Using a json from the server . The code looks something like this
function loadWorkFlowRules() {
var wf_id = <?php echo $wf->id; ?>;
$.post("/api/wfengine/get_wf_rules/", {
wf_id: wf_id
}, function(result) {
var wf_rules = JSON.parse(result).data;
if (makeView(wf_rules)) {
toastr.success('The Rules are Successfully Loaded!');
} else
toastr.info('Welcome to Work Flow Editor');
});
}
function makeView(wf_rules) {
//console.log(wf_rules);
var html_str = '',
response = false;
$.each(wf_rules, function(key, value) {
if (value.length > 0) {
$.each(value, function(key1, value1) {
var ui_l1 = '<li class="alert mar" data-id="' + value1.id + '" data-name="' + value1.name + '" style=""><div class="dd-handle state-main">' + value1.name + '<span class="cust-close" data-dismiss="alert" aria-label="Close"><i class="fa fa-times"></i></span></div><ol>';
html_str = html_str + ui_l1;
if (value1.children.length > 0) {
$.each(value1.children, function(key2, value2) {
$.each(value2, function(key3, value3) {
var ui_l2 = '<li class="alert mar" data-id="' + value3.id + '" data-name="' + value3.name + '" style=""><div class="dd-handle state-main">' + value1.name + '<span class="cust-close" data-dismiss="alert" aria-label="Close"><i class="fa fa-times"></i></span></div><ol>';
html_str = html_str + ui_l2;
if (value3.children.length > 0) {
$.each(value3.children, function(key4, value4) {
if (value4.length > 0) {
var ui_l3 = '<li class="dd-item alert mar action" data-id="' + value4[0].id + '" data-name="' + value4[0].name + '" data-api="' + value4[0].api + '" data-url="' + value4[0].url + '" data-json="' + value4[0].json + '" style=""><div class="dd-handle">' + value4[0].name + '<span class="cust-close" data-dismiss="alert" aria-label="Close"><i class="fa fa-times"></i></span> <span class="edit cust-close" data-toggle="modal" data-target="#editAction" ><i class="fa fa-pencil"></i></span></div></li>';
html_str = html_str + ui_l3;
}
})
}
html_str = html_str + '</ol></li>';
});
})
}
html_str = html_str + '</ol></li>';
});
$('.contract_main').html(html_str);
response = true;
} else
response = false;
});
return response;
}
HTML
<div class="dd">
<ol class="dd-list simple_with_drop vertical contract_main">
</ol>
</div>
I got into a situation where Ill have to Bind the data element of the child <li> with an HTML MODAL popup , So that if the value in Modal is updated it shoud change in the Object/Dom also .
I was recommended to use VueJs.
I have went through! the basics of the VueJs , But that didn't cover how I ccan bind complete list from a Json ,
Any help in how I can do this would be great
Currently I don't see any structure of Vue.Js in your code and you are manipulating the JSON data and constructing the HTML in the JS code itself. You can do it in vue way, where you will create an Vue instance, do loading of data in Vue methods and use Vue syntax to iterate over data and other things. One Simple example you can see in this fiddle or in below code:
new Vue({
el: '#app',
data: {
jsonData: []
},
mounted () {
this.loadJsonData();
},
methods: {
loadJsonData(){
setTimeout(()=>{
this.jsonData = ["first", "Second", "Third", "And So On"]
}, 300)
}
}
})
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="app">
<ul>
<li v-for="data in jsonData">{{data}}</li>
</ul>
</div>
You can look at vue-hackernews to understand more about structuring of code, How to fetch data from remote APIs in JSON format and display it.

Categories

Resources