Alphabetize javascript for loop - javascript

I'm getting desired results, but need to order them alphabetically. I am unsure what to put in exactly in the code:
function showClients(data) {
var html = '';
for (var clientId in data) {
html += '<p>' + clientId;
html += data[clientId].connected ? ' connected' : ' disconnected';
html += '</p>';
}
if (!html) {
html += '<p>No clients connected</p>';
}
$('#connected_clients').html(html);
}

If I've got the layout of the data structure right, it is a key/value object, which in turn contains objects that have information such as connected.
In that case you can use Object.keys to get the keys first, sort those Object.keys(data).sort(), and create the html from there. For example:
function showClients(data) {
var html = Object.keys(data).sort().reduce(function(h, clientId){
return h + '<p>' + clientId
+ (data[clientId].connected ? ' connected' : ' disconnected')
+ '</p>';
}, '')
|| '<p>No clients connected</p>';
$('#connected_clients').html(html);
}
function showClients(data) {
var html = Object.keys(data).sort().reduce(function(h, clientId){
return h + '<p>' + clientId
+ (data[clientId].connected ? ' connected' : ' disconnected')
+ '</p>';
}, '')
|| '<p>No clients connected</p>';
$('#connected_clients').html(html);
}
showClients({Client3:{connected:true},Client1:{connected:true},Client2:{connected:false}});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id=connected_clients></div>

Call sort on the data like Array.prototype.sort(data). If you don't pass a compare function, it will sort the elements alphabetically.
function showClients(data) {
var html = '';
for (var clientId in Array.prototype.sort.call(data)) {
html += '<p>' + clientId;
html += data[clientId].connected ? ' connected' : ' disconnected';
html += '</p>';
}
if (!html) {
html += '<p>No clients connected</p>';
}
$('#connected_clients').html(html);
}

Related

loop from json files and search then get the value via jquery and json

I have a bit of a question. which is a loop.
I have a simple looping which when I clicked some numbers and it will search and loop through out my json file.
here is my code
function showSortedRoute(){
$.getJSON('my.json', function(data) {
var $resultHTML = $("#divResult");
var result = "";
result = '<ul class = "list clearfix">';
$.each(data, function (key, val){
if (val.area_id == getRuoute) {
var image = val.image;
var structure_name = val.name;
var copy = val.copy;
var address = val.address;
var access = val.access;
var type = val.type;
var getarea = val.area;
result += '<div class="iconArea">';
result += '<h4>' + name + '</h4>';
result += '<h4><b>' + getarea + '</b></h4>';
result += '</div>';
result += '<p class="catch">' + copy + '</p>';
result += '<dl class="detailArea clearfix">';
result += '<dd>' + address + '</dd>';
result += '<dd>' + access + '</dd>';
result += '</dl>';
result += "</ul>";
$resultHTML.html(result);
} else {
alert("No area ID Found" + getRoute);
}
});
});
}
this does not give me any results, saying no area ID found, but in
alert("no area id found" + getRoute);
and the alert shows displays like four times.
I can check that the value is the same.
code for matching up with integers with json is not working.
There's a few errors in your code:
getRuoute in this line: if(val.area_id == getRuoute){ seems to be
undeclared variable
name in this line: result += '<h4>' + name + '</h4>'; is also
undeclared
getRoute in this line: alert("No area ID Found" + getRoute);
seems to be undeclared variable
Here is corrected and optimized version:
$.getJSON('my.json', function(data) {
var $resultHTML = $("#divResult"),
result = '<ul class = "list clearfix">';
$.each(data, function (key, val){
if (val.area_id == 'getRuoute') { // check type and name of 'getRuote', maybe 'getRoute'?
var image = val.image,
structure_name = val.name,
copy = val.copy,
address = val.address,
access = val.access,
type = val.type,
getarea = val.area;
result += '<div class="iconArea">';
result += '<h4>' + structure_name + '</h4>';
result += '<h4><b>' + getarea + '</b></h4>';
result += '</div>';
result += '<p class="catch">' + copy + '</p>';
result += '<dl class="detailArea clearfix">';
result += '<dd>' + address + '</dd>';
result += '<dd>' + access + '</dd>';
result += '</dl>';
result += "</ul>";
$resultHTML.html(result);
} else {
alert("No area ID Found" + getRoute);
}
});
});

ordered list; working with javascript and json

I'm a junior web developer and I want to understand what json file does, as I have no idea. So I am following a tutorial from lynda.com
It seems very simple, I want to display the array elements within the variable info, but for some reason, it's adding another count after each item of the array!!! I have checked and compared the code with the tutorial, and it's still appearing wrong.
I have added the code on JSFiddle:
https://jsfiddle.net/meyvz462/
Those are my loops:
for (var i = 0; i <= info.links.length; i++) {
for (key in info.links[i]) {
if (info.links[i].hasOwnProperty(key)) {
output += '<li>' +
'<a href = "' + info.links[i][key] +
'">' + key + '</a>' +
'<li>';
} // hasOwnProperty ckeck
} //for each object
} //for each array element
I guess it is what it must be wrong....
Thank you!!!!
The closing tag is wrong.
output += '<li>' +
'<a href = "' + info.links[i][key] +
'">' + key + '</a>' +
'<li>';
has to be
output += '<li>' +
'<a href = "' + info.links[i][key] +
'">' + key + '</a>' +
'</li>';
You have missed a closing </li> at the end (https://jsbin.com/yasenivege/1/edit?js,console,output):
var info = {
"full_name" : "Someone Else",
"title" : "Web Developer",
"links" : [
{ "blog" : "http://iviewsource.com" },
{ "facebook" : "http://facebook.com/iviewsource" },
{ "podcast" : "http://feeds.feedburner.com/authoredcontent" },
{ "twitter" : "http://twitter.com/planetoftheweb" },
{ "youtube" : "http://www.youtube.com/planetoftheweb" }
]
};
var output = '';
for (var i = 0; i <= info.links.length; i++) {
var element = info.links[i];
for (var key in element) {
console.log(element[key]);
if (element.hasOwnProperty(key)) {
output += '<li>' +
'<a href = "' +element[key] +
'">' + key +'</a>'+
'</li>';
}// hasOwnProperty ckeck
} //for each object
} //for each array element
var update = document.getElementById('linksGroup');
console.log(output)
update.innerHTML = output;

Simple jQuery if statement, API returns 'null'

Using the Sunlight Congress API to pull a list of representatives, I'd like to return folks' nicknames if they are used. If a representative doesn't use a nickname, the API returns 'null'.
I'm messing up the syntax for the if statement. Here's my most recent misguided approach:
if (rep.nickname == 'null'){myFolks += rep.first_name + ' ';}
 
Here's the full context:
$(document).ready(function () {
$('#rep-lookup').submit(function(e){
e.preventDefault();
var $results = $('#rep-lookup-results'),
zipcode = $('#txt-zip').val(),
apiKey = '_YOUR_API_KEY';
var requestURL = 'http://congress.api.sunlightfoundation.com/legislators/locate?callback=?';
// collect the data
$.getJSON(requestURL, {
'apikey' : apiKey,
'zip' : zipcode,
}, function(data){
if (data.results && data.results.length > 0) {
var myFolks = '<p>Here are your Congress folk:</p>';
$.each(data.results, function(i, rep) {
myFolks += '<p>';
myFolks += '<a href="' + rep.contact_form + '" target="_blank">';
myFolks += rep.nickname;
if (rep.nickname == 'null'){myFolks += rep.first_name + ' ';}
myFolks += rep.last_name + ' ';
myFolks += '</a>';
myFolks += '</p>';
});
myFolks += '<p>Please write to them in support of this legislation.</p>';
$results.html(myFolks);
} else {
$results.html('<p>None found for zip code ' + zipcode + '. Please try again.</p>');
}
});
});
});
myFolks += (rep.nickname && rep.nickname !== "null") ? rep.nickname : rep.first_name + ' ';
via: #tomcreighton

How to use other parameters with an exception included

I have this function:
function searchItem(e, pageNumber){
e.preventDefault();
searchString = searchBox.value;
article = document.getElementById("homeSection");
var xmlhttp = getXmlHttpRequestObject();
var string = '';
if(xmlhttp){
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
var response = JSON.parse(xmlhttp.responseText);
for(var i=0; i<response.length; i++){
var price = parseFloat(response[i].Price);
string += '<section class="searchResult">';
string += '<p class="photo"><img src="' + response[i].Photo + '"></p>';
string += '<section>';
string += '<h1 class="name">' + response[i].Name + '</h1>';
string += '<p class="price">£' + price.toFixed(2) + '</p>';
string += '<p class="description">' + response[i].Description + '</p>';
string += '<p class="productID">ID: ' + response[i].ID + '</p>';
string += '<p class="quantity">Quantity: ' + response[i].Quantity + '</p>';
string += '</section>';
string += '</section>';
if(pageNumber != 1){
string += '<section><button id=previousPage>Previous</button><button id=nextPage>Next</button></section>';
}
}
article.innerHTML = '<h1>Search</h1><section><h1 class="bottomBorder">You searched for: "' + searchString + '"</h1></section>';
article.innerHTML += string;
}
};
xmlhttp.open("POST", "search.php?search=" + searchString, false);
xmlhttp.send("&rpp=" + rowsPerPage + "&last=" + lastPage + "&page=" + pageNumber);
}
}
What i am curious about is how to call the function because it has an exception in it.
It worked fine when i was using it in a javascript event:
searchButton.addEventListener("click", searchItem);
but when i tried calling the function with parameters like this it didn't work, it tells me that e is not defined:
searchButton.addEventListener("click", function(){
searchItem(1);
});
Which i do understand because i haven't passed through a parameter for e but i want to know is why it works as an event without a pseudo function and how i should call it with a pseudo function.
The function requires the event as the first argument. This is set when using the function itself as the click handler, but when you create your own click handler, you need to capture the event and explicitly pass it:
searchButton.addEventListener("click", function(e){
// capture the event object--^
searchItem(e, 1);
// ^ pass it to the function
});

how to display json content in li format in phonegap

i can get the json in the following format
[{"data":{"id":"1","user_name":"StudentA","book":"123","role":"Student"}},
{"data":{"id":"3","user_name":"StudentB","book":"456","role":"Student"}}]
how can i use the data to present like the image below, where the first line is username and second line is book
<button type="button" id="test">Test 123</button>
<ul id="studentList" data-role="listview" data-filter="true"></ul>
var serviceURL = "http://mydomain.com/";
var students;
$("#test").click(function()
{
getStudentList();
});
function getStudentList() {
$.getJSON(serviceURL + 'getStudents.php', function(data) {
$('#studentList li').remove();
students = data.user_name;
$.each(students, function(index, student) {
$('#studentList').append('<li>' +
'<h4>' + student.user_name + ' ' + student.password + '</h4>' +
'<p>' + student.user_name + '</p>' +
'</li>');
});
$('#studentList').listview('refresh');
});
}
may i ask if the codes above correct?
you are naming response as data..since you response is in array [] you have to loop data first.. get its object which is data again ..
[{"data":{"id":"1","user_name":"StudentA","book":"123","role":"Student"}},
//-^^^^---here
and get the correponding name and password object in the loop...you can get that by . operator.. so inside loop, student.data.user_name gives you username , student.data.book gives you book and similar for others...
try this...
$.getJSON(serviceURL + 'getStudents.php', function(data) {
$('#studentList li').remove();
//students = data.user_name;
$.each(data, function(index, student) {
$('#studentList').append('<li>' +
'<h4>' + student.data.user_name +'</h4>' + //here get username
'<p>' + student.data.book + '</p>' + //here get book
'</li>');
});
$('#studentList').listview('refresh');
});
I have done it like that based on your input, you just need to include it into your code. I don't know what you mean by 'second line is book' since there is no book included in your json input + you are trying to access 'student.data.password' which is also not present in input.
Simple version of jsFiddle http://jsfiddle.net/2KMd9/
var json =[{"data":{"id":"1","user_name":"StudentA","book":"123","role":"Student"}},
{"data":{"id":"3","user_name":"StudentB","book":"456","role":"Student"}}];
var students = json;
$.each(students, function(index, student) {
$('#studentList').append('<li>' +
'<h4>' + student.data.user_name + '</h4>' +
'<p>' + student.data.role + '</p>' +
'</li>');
});
So for your needs:
function getStudentList() {
$.getJSON(serviceURL + 'getStudents.php', function(data) {
$('#studentList li').remove();
$.each(data, function(index, student) {
$('#studentList').append('<li>' +
'<h4>' + student.data.user_name + '</h4>' +
'<p>' + student.data.role + '</p>' +
'</li>');
});
$('#studentList').listview('refresh');
});
}

Categories

Resources