sort jquery result alphabetically - javascript

I am trying to make a dynamic list of my blog posts. I need the list to be displayed alphabetically. The current code is working okay, but gave me a chronological list. How can I arrange my list alphabetically. Current code is given below. It is for blogger blog and I used kimonolabs to make the API used in this code. The feed is in jason. (In blog page area I first created a blank html list and then used below code to insert data. Html is also given.) What should I do to make the result alphabetical.
jQuery.ajax({
"url":"https://www.kimonolabs.com/api/djwmp1p8?apikey=P1DP0fILX0ou5GnXR6DRbbRmkFuQNC0G",
"crossDomain":true,
"dataType":"jsonp",
//Make a call to the Kimono API following the "url"
'success': function(response){
// If the call request was successful and the data was retrieved, this function will create a list displaying the data
jQuery(".panel-heading").html(response.name);
//Puts the API name into the panel heading
var collection = response.results.collection1;
for (var i = 0; i < collection.length; i++){
// Traverses through every element in the entire collection
jQuery(".list-group").append('<li class="list-group-item">' +'<a href='+collection[i].property1.href +'>'+ collection[i].property1.text + '</a>' +'</li>');
// adds the text and the links from the first property into the list
}
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<div class="container padding">
<div class="panel panel-info">
<div class="panel-heading"></div>
<ol class="list-group">
</ol>
</div>
</div>

As response.results.collection1 is array, and you want it to order in alphabetical order, you need to sort by each item's property1.text:
collection.sort(function(item1, item2) {
return item1.property1.text > item2.property1.text ? 1 : -1;
});
jQuery.ajax({
"url":"https://www.kimonolabs.com/api/djwmp1p8?apikey=P1DP0fILX0ou5GnXR6DRbbRmkFuQNC0G",
"crossDomain":true,
"dataType":"jsonp",
//Make a call to the Kimono API following the "url"
'success': function(response){
// If the call request was successful and the data was retrieved, this function will create a list displaying the data
jQuery(".panel-heading").html(response.name);
//Puts the API name into the panel heading
var collection = response.results.collection1;
// VVVV Sort it by item.property1.text before print out.
collection.sort(function(item1, item2) {
// If item1.property1.text's alphabetical order is larger than item2's return 1, otherwise return 0.
return item1.property1.text > item2.property1.text ? 1 : -1;
//return item1.property1.text.localeCompare(item2.property1.text) > 0 ? 1 : -1;
});
for (var i = 0; i < collection.length; i++){
// Traverses through every element in the entire collection
jQuery(".list-group").append('<li class="list-group-item">' +'<a href='+collection[i].property1.href +'>'+ collection[i].property1.text + '</a>' +'</li>');
// adds the text and the links from the first property into the list
}
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<div class="container padding">
<div class="panel panel-info">
<div class="panel-heading"></div>
<ol class="list-group">
</ol>
</div>
</div>

http://jsfiddle.net/03f1ehsf/
collection.sort(function(a,b){ return b.property1.text>a.property1.text?0:1});

Related

Appending a col div with jQuery in a for loop only gives me results on the first row

I am retrieving an AJAX dump from a Django python Function.
Then, I am trying to reflect the data on a bootstrap row + column table.
However, when using append() in an array list, I only seem to get the first row of the dump. When I remove the 2nd for loop, the dump works fine, just does not give me the rows of the months that I need.
I have more than one row worth of data, definitely.
What could be causing this?
//html code
<div id="category_filtered_list">
<div class="row report_row mockup" id="category_mockup">
<div class="col-md-1 name"></div>
<div class="col-md-1 code"></div>
<div class="col-md-1 forecasted"></div>
<div class="col-md-1 running_total"></div>
<div class="monthsRows" id="monthsRows"></div>
</div>
</div>
//Ajax JS function
$.post(
"",
{
"getcategories": true,
'date-from': date_from,
'date-to': date_to
},
function(response) {
$("#category_filtered_list .report_row.product").remove()
data = JSON.parse(response);
for (var i=0; i<data.length;i++){
obj = data[i]
var mockup = $('#category_mockup')
var temp_mockup = $(mockup).clone()
$("#category_filtered_list").append(temp_mockup)
$(mockup).attr('id',"temp_product");
var temp_prod = $("#temp_product")
$(temp_prod).find('.name').html(obj.category_name)
$(temp_prod).find('.code').html(obj.category_code)
$(temp_prod).find('.minor').html(obj.category_minor)
$(temp_prod).find('.parent').html(obj.category_parent)
$(temp_prod).find('.forecasted').html(obj.category_forecasted)
$(temp_prod).find('.running_total').html(obj.products_count)
//this for loop is causing the issue ******* when removed, the rest of the code works fine. Please note that obj.prods_num_per_month is an array
for (i=0; i<=obj.prods_num_per_month.length; i++){
$(temp_prod).find('.monthsRows').append(
$('<div class="col-xs-1">').html(obj.prods_num_per_month[i])
);
}
$(temp_prod).removeClass('mockup');
$(temp_prod).addClass('product');
$(temp_prod).attr('id','')
}
}
).done(function(){
$("#filtering .message_loading").html("Completed! <i class='far fa-smile text-success'></i>")
$("#filtering .message_loading").addClass("fading")
$("#export_button").show()
setTimeout(function(){ $("#filtering .message_loading").html('') }, 5000);
});
I am expecting to get all rows with relevant data, but instead, I am just getting the first row.
Not my proudest moment... So.. The code works fine actually, but I have declared 'i' as the index for both 'for' loops, causing the main loop to terminate early..
I changed the index for the 2nd for loop and it's up and running as intended.
2 hours of debugging...Really not my proudest moment. Good news is it's fixed!

How to display the last four blog posts using JSON API in div tag

How do I display the latest four blog post WordPress API in HTML
HTML:
<div id="content" class="content"></div>
JavaScript:
<script>
$(document).ready(function() {
$.getJSON("https://startupet.com/blog/wp-json/wp/v2/posts", function(data) {
console.log(data);
});
})
</script>
I'm getting image post and title
JSON file: https://startupet.com/blog/wp-json/wp/v2/posts
You can use slice with a negative number to get the element from the end of the array.
In this example , dummy api is returning a response and slice(-4) is used to get the last 4 elements, then iterate that array and create the dom
$.getJSON("https://jsonplaceholder.typicode.com/posts", function(data) {
let string = '';
data.slice(-4).forEach(function(item) {
string += `<div>${item.title}</div>`
})
$("#content").append(string)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="content" class="content">
</div>
You can sort the array based on the timestamp and slice it with the number of items you require.
Next is to iterate through the result and display however you want in the html
$(document).ready(function(){
$.getJSON( "https://startupet.com/blog/wp-json/wp/v2/posts",
function(data) {
const result = data.sort((a,b) => (a.date > b.date)).slice(Math.max(data.length - 4, 1));
console.log(result); // Your Result contains the last 4 posts sorted by date
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="content" class="content">
</div>

How to send the data of a list group item to a controller function using an http get request

I'm writing an application in c# using the asp.net mvc web application platform. In my index.cshtml I have a list group div called 'results'. When a user clicks one of the items in the div, I would like to send the data in the item to a function in an api controller. I've attempted to do this, but when I click on an item, I get no response at all.
<script>
$('.list-group-item').on('click', function () {
var artist = $(this).val();
$.get("/api/Search/related?artistId=" + artist.ArtistId, function (data) {
$("results").html("");
if (data.Data.length > 0) {
for (var i = 0; i < data.Data.length; i++) {
$("#results").append('<button type= "button" class="list-group-item">' + data.Data[i] + '</button>');
}
}
else {
$("#results").html("<p style=\"text-align:center\">No results were found!! :(</p>");
}
});
});
</script>
The contents of the 'results' div are populated correctly with another javascript function. Here is the html for results:
<div class="row">
<div class="col-lg-6 col-lg-offset-3">
<div class="list-group" id="results">
</div>
</div>
</div>

Framework7: Delete items of an array with swipeout

I tried app developing with Framework7.
I print my array (list) in this way:
if (list != null){
for (var i=0; i<list.length; i++){
output = output + '<li class="swipeout"><div class="item-content swipeout-content"><div class="item-inner"><div class="item-title-row"><div class="item-title">' + list[i].name + '</div></div><div class="item-subtitle">' + new Date(list[i].fDate).toLocaleDateString() + '</div></div></div><div class="swipeout-actions-right">Delete</div></li>';
}
}
$$('#liste').html(output);
When I swipeout an entry, the entry will disappear but he is still in the array.
This is to handle the remove-event:
$$('.swipeout').on('deleted', function () {
myApp.alert('Item removed');
});
How can I get the index of the element to remove it also from the array?
Alternatively, is there an other way to solve this problem?
Thank you!
Markus
If I were you, I'd rather use Framework7's view engine to render the swipeout items and take advantage of the #index helper. Click here for further information.
In your markup, you'd have something similiar to this:
<div class="list-block">
<ul>
{{#each item in list}}
<li class="swipeout">
<!-- Usual list element wrapped with "swipeout-content" -->
<div class="swipeout-content">
<!-- Your list element here -->
<div class="item-content">
<div class="item-media">...</div>
<div class="item-inner">...</div>
</div>
</div>
<!-- Swipeout actions right -->
<div class="swipeout-actions-right">
<!-- Swipeout actions links/buttons -->
<a href="#" data-index={{#index}}>Action 1</a>
<a class="swipeout-close" href="#" data-index={{#index}}>Action 2</a>
</div>
</li>
{{/each}}
Notice that I'm using the "each" helper along with "#index" to render the items and put an attribute on them with the id. But you can still achieve the same objective by using the "i" variable inside the for loop:
if (list != null){
for (var i=0; i<list.length; i++){
output = output + '<li class="swipeout"><div class="item-content swipeout-content"><div class="item-inner"><div class="item-title-row"><div class="item-title">' + list[i].name + '</div></div><div class="item-subtitle">' + new Date(list[i].fDate).toLocaleDateString() + '</div></div></div><div class="swipeout-actions-right"><a href="#" class="swipeout-delete" data-index='+i+'>Delete</a></div></li>';
}
}
When the event is fired:
$$('.swipeout').on('deleted', function () {
var $thisAction = $(this);
// Here you delete the item
delete list[$thisAction.data('index')];
myApp.alert('Item removed');
});
In this case you can't use Array.slice because if you delete item 2 from the markup, the element with the index 3 will replace item 2. The problem with the above approach is that you have to take care of the "holes" in your array. A much better approach would be to use a two-way binding framework, such as VueJs.

How to add Contact List data into PhoneGap ListView

I have a javascript function which will read the device ContactList and add them into a javascript array.In my HTML page i have taken a listview.Now as per my requirement i have to add these array data into the listview by jquery dynamically which i am not able to do .I am not able to see anything on the screen of the mobile on launching the app..
Here is my javascript code to read from Mobile's contact list..
function onDeviceReady() {
// specify contact search criteria
var options = new ContactFindOptions();
options.filter=""; // empty search string returns all contacts
options.multiple=true; // return multiple results
filter = ["displayName"]; // return contact.displayName field
// find contacts
navigator.contacts.find(filter, onSuccess, onError, options);
}
var names = [];
// onSuccess: Get a snapshot of the current contacts
//
function onSuccess(contacts) {
for (var i=0; i<contacts.length; i++) {
if (contacts[i].displayName) { // many contacts don't have displayName
names.push(contacts[i].displayName);
}
}
alert('contacts loaded');
}
and here is my HTML listview..
<div data-role="page" id="home" data-theme="c">
<div data-role="content">
<div id="header" class="header">
<h1>Contact Directory</h1>
</div>
<ul data-role="listview" id="contactlist" data-theme="a">
</ul>
</div>
</div>
So, My question is how can i add the array values into the listview by jquery dynamically..
Thanks..
Couple of ways, but here is one way.
Create a simple string variable to hold your LIs.
Loop over names and append to the string <li> + names[x] + </li> where X is your loop counter.
Use jQuery to get the UL dom and then do .html(s) where s is your string.
Basically you are injecting <li>...</li><li>...</li> into your UL.
The last step is to refresh the list view so jQuery displays it correctly. This is done with the refresh API, defined here: http://api.jquerymobile.com/listview/#method-refresh

Categories

Resources