Can this be turned into a for loop? - javascript

I would like to clean this up with a For loop. What would be the most efficient way coding this out?
I'm creating a search form that looks through a database for the specific form criteria. The way I have it coded would only work for the 8 Fields. But it is possible for the search form to have more then 8. For now though, I'd like to be able to map the results and display in a results page.
This is what I tried. This did not work at all and probably make no sense to anyone lol.
var obj =data[0]
$.get("obj", {data: $('select["Fields.DisplayName" + Fields.DataValue]').val()},
function(data){
$.each(data, function(i, item) {
alert(item);
});
}
);
This works for getting the data and displaying it how I'd like.
var obj = data[0];
document.getElementById("test").innerHTML =
"<p>"+ obj.Fields[0].DisplayName + ": " + obj.Fields[0].DataValue + "</p>" +
"<p>" + obj.Fields[1].DisplayName + ": " + obj.Fields[1].DataValue + "</p>" +
"<p>"+ obj.Fields[2].DisplayName + ": " + obj.Fields[2].DataValue + "</p>" +
"<p>"+ obj.Fields[3].DisplayName + ": " + obj.Fields[3].DataValue + "</p>" +
"<p>" + obj.Fields[4].DisplayName + ": " + obj.Fields[4].DataValue + "</p>" +
"<p>" + obj.Fields[5].DisplayName + ": " + obj.Fields[5].DataValue + "</p>" +
"<p>"+ obj.Fields[6].DisplayName + ": " + obj.Fields[6].DataValue + "</p>" +
"<p>" + obj.Fields[7].DisplayName + ": " + obj.Fields[7].DataValue + "</p>"
;
The next problem is if there is more then 1 data object. Currently I have it set to loop through the first object, but when I remove that I get cannot read property of '0' undefined.

Sure.
var html = "";
obj.Fields.forEach(({DisplayName, DataValue}) => {
html += `<p>${DisplayName}: ${DataValue}</p>`;
});
document.getElementById("test").innerHtml = html;

Use Array.map() and join the results:
var fields = data[0].Fields ;
document.getElementById("test").innerHTML = fields
.map(function(field) {
return '<p>' + field.DisplayName + ': ' + field.DataValue + '</p>';
})
.join('\n');

Related

Trouble with jQuery loop through array of objects

I'm trying to nest 3 divs within a "row" div.
I had this working in "long format" (multiple var's instead of looping through the array). I've refactored my code and now I don't get any error codes AND my code does not append to the HTML file. When I console log I get an array with 3 objects. I'm sure i'm missing something minor.
Anyways some help would be great!
<div class="row">
**nested divs go here.
</div>
$(document).ready(function() {
$.get("http://api.openweathermap.org/data/2.5/forecast/daily?id4726206&cnt=3", {
APPID: "MY API KEY",
lat: 29.423017,
lon: -98.48527,
units: "imperial"
}).done(function(data) {
var stationId = data.city.name;
// Stattion Name
$('#station').append(stationId);
//console.log(data);
var forecast = data.list;
//Wind Direction in Compass Format
function getDirection(dir) {
var compass = ['N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW'];
var result = Math.floor((360 - dir) / 22.5);
return compass[result];
}
//Forecast Variables
$.each(forecast, function(i, v) {
var html = '';
html += "<div class='col-sm-3 wInfo'>" + "<div class='title'>High / Low</div>";
html += "<div class='cTemp'>" + (Math.ceil(forecast[i].temp.max)) + '°';
html += " / " + (Math.ceil(forecast[i].temp.min)) + '°' + "</div>";
html += "<div class='tempIcon'>" + "<img src='http://openweathermap.org/img/w/" + forecast[i].weather[0].icon;
html += ".png' alt=''></div>" + "<div class='conditions' id='castId'>" + '<span class="cond">' + forecast[i].weather[0].main;
html += "</span>: " + "<span>" + forecast[i].weather[0].description + '</span>' + "</div>";
html += "<div class='conditions'>" + "<span class='cond'>Humidity: </span>" + "<span>" + forecast[i].humidity + "%</span></div>";
html += "<div class='conditions'>" + "<span class='cond'>Wind: </span>" + "<span>" + (Math.floor(forecast[i].speed));
html += " mph / " + getDirection(forecast[i].deg) + "</span></div>" + "<div class='conditions'>";
html += "<span class='cond'>Pressure: </span>" + "<span>" + forecast[i].pressure + "</span></div>";
return html;
});
$('.forecast').append(forecast);
console.log(forecast);
});
});
You are trying to append the array forecast in html. which wont work. You should declare the html variable outside and then use it in append function.
I will also recommend to use string builder logic using array and then convert it to string and append it. remember string concatenation is heavy operator as it creates new instance of elememt every time concatenation is done :
var html = [];
$.each(forecast, function(i, v) {
html.push("<div class='col-sm-3 wInfo'>" + "<div class='title'>High / Low</div>");
html.push("<div class='cTemp'>" + (Math.ceil(forecast[i].temp.max)) + '°');
html.push(" / " + (Math.ceil(forecast[i].temp.min)) + '°' + "</div>");
html.push("<div class='tempIcon'>" + "<img src='http://openweathermap.org/img/w/" + forecast[i].weather[0].icon);
html.push(".png' alt=''></div>" + "<div class='conditions' id='castId'>" + '<span class="cond">' + forecast[i].weather[0].main);
html.push("</span>: " + "<span>" + forecast[i].weather[0].description + '</span>' + "</div>");
html.push("<div class='conditions'>" + "<span class='cond'>Humidity: </span>" + "<span>" + forecast[i].humidity + "%</span></div>");
html.push("<div class='conditions'>" + "<span class='cond'>Wind: </span>" + "<span>" + (Math.floor(forecast[i].speed)));
html.push(" mph / " + getDirection(forecast[i].deg) + "</span></div>" + "<div class='conditions'>");
html.push("<span class='cond'>Pressure: </span>" + "<span>" + forecast[i].pressure + "</span></div></div>");
});
$('.forecast').append(html.join(""));

Getting a sub-class out of an array

I am learning how to code around a project that I am trying to build. So heres a snippet of some JavaScript that I'm executing with Google Maps API:
for (i = 0; i < results.length; i++) {
console.log("Formatted Address: "+ results[i].formatted_address + "\n" +
"Geometry: "+ results[i].geometry.location + "\n" +
"Types: "+ results[i].types + "\n" +
results[i].address_components[0].types + ": " + results[i].address_components[0].long_name + "\n" +
results[i].address_components[1].types + ": " + results[i].address_components[1].long_name + "\n" +
results[i].address_components[2].types + ": " + results[i].address_components[2].long_name + "\n" +
results[i].address_components[3].types + ": " + results[i].address_components[3].long_name + "\n" +
results[i].address_components[4].types + ": " + results[i].address_components[4].long_name + "\n" +
results[i].address_components[5].types + ": " + results[i].address_components[5].long_name + "\n" +
results[i].address_components[6].types + ": " + results[i].address_components[6].long_name + "\n" +
results[i].address_components[7].types + ": " + results[i].address_components[7].long_name + "\n" +
results[i].address_components[8].types + ": " + results[i].address_components[8].long_name + "\n" +
results[i].address_components[9].types + ": " + results[i].address_components[9].long_name
);
formattedAddress = results[i].formatted_address;
coordinates = results[i].geometry.location;
types = results[i].types;
// component = results[i].address_components[0].types;
no = i+1;
output += "<li>";
output += "<p><i>"+ no +"</i></p>"
output += "<p><b>"+ formattedAddress +"</b></p>";
output += "<p>"+ coordinates +"</p>";
output += "<p>"+ types +"</p>";
output += "</li>";
//console.log("results for "+ [i] + " :" + output);
$("#list-locations").html(output);
}
I am trying to read & output the address components (.types & .long_name) which can vary length depending on the search term. Some search terms will only return 1 types & long_name field, whereas other search terms could return 7 or 8.
I am ultimately looking to add it to my output variable.
Here is an example JSON Return:
{
"types":["locality","political"],
"formatted_address":"Winnetka, IL, USA",
"address_components":[{
"long_name":"Winnetka",
"short_name":"Winnetka",
"types":["locality","political"]
},{
"long_name":"Illinois",
"short_name":"IL",
"types":["administrative_area_level_1","political"]
},{
"long_name":"United States",
"short_name":"US",
"types":["country","political"]
}],
"geometry":{
"location":[ -87.7417070, 42.1083080],
"location_type":"APPROXIMATE"
},
"place_id": "ChIJW8Va5TnED4gRY91Ng47qy3Q"
}
In this example address_components[2].long_name would return "United States", whereas address_components[3].long_name would return undefined.
How can I add a counter, so that ...address_components[j].long_name is the length of the no. of fields in the specific search term (j being that number)?
OK, so I solved the problem by doing the following:
for (i = 0; i < results.length; i++) {
formattedAddress = results[i].formatted_address;
coordinates = results[i].geometry.location;
types = results[i].types;
no = i+1;
output += "<li>";
output += "<H1><i>"+ no +"</i></H1>"
output += "<p><b>"+ formattedAddress +"</b></p>";
output += "<p>"+ coordinates +"</p>";
output += "<p>"+ types +"</p>";
for (j = 0; j < results[i].address_components.length; j++) {
comp = results[i].address_components[j].types;
compCont = results[i].address_components[j].long_name;
output += "<p>"+ comp +": " + compCont +"</p>";
}
output += "</li>";
$("#list-locations").html(output);
}
As per #localghost comments, if I went less than or equal to I would need the -1

jquery $.each not giving all the information in the table

Fiddle
I want to put the names of all record in my array into a table my array isn't index correctly so i used $.each instead of iterating over the using for loop. My problem is I only get to show the last element but if i try to show a value that is existing to both the array it is showing correctly.
What am i missing in this code.
Any idea is appreciated
This is my javascript
for (var i = 0; i < name.length; i++) {
var names = name[i].Names;
$.each(names, function (item, names) {
tr = $('<tr class=""/>');
//console.log(complainant[obj]);
//var names = complainant[obj];
//if(names.hasOwnProperty('fname')){
console.log(names.suffix);
var acronymc;
var upper = names.mname.toUpperCase();
if (upper) {
var matches = upper.match(/\b(\w)/g);
//var matches = upper.replace(/^(\S+)\s+(\S).*/, '$1 $2.');
//acronym = upper.slice(0,1);
var acronym1 = matches.join('');
acronymc = acronym1.slice(-1);
} else {
acronymc = '';
}
tr.append("<td id=''>" + "<span id='fname'>" + names.fname + "</span>" + " " + "<span id='mname'>" + acronymc + "</span>" + " " + "<span id='lname'>" + names.lname + "</span>" + " " + "<span id='suffix'>" + names.suffix + "</span>" + "</td>");
tr.append("<td id=''>" + '<span id="street">' + names.street + '</span>' + " " + '<span id="brgy">' + names.brgy + '</span>' + " " + '<span id="town">' + names.town + '</span>' + " " + '<span id="city">' + names.city + '</span>' + "</td>");
tr.append("<td id=''>" + names.contactnum + "</td>");
tr.append("<td id=''>" + "<a href='#' class='editcomplainant'>Edit</a>" + "/" + "<a href='#' class='delete'>Delete</a>" + "</td>");
//}
});
$("#nameslist").append(tr);
}
Put the $('#nameslist').append(tr); call inside the $.each block.
Here is a way of improving the creation of tds:
var html =
"<td>" +
"<span id='fname'/> " +
"<span id='mname'/> " +
"<span id='lname'/> " +
"<span id='suffix'/>" +
"</td>";
var td = $(html);
td.find('#fname').text(names.fname);
td.find('#mname').text(acronymc);
td.find('#lname').text(names.lname);
td.find('#suffix').text(names.suffix);
tr.apppend(td);
Why is this better (imho)?
You will not create unintentional html tags by having < and > inside the variables.
Appropriate escaping (auml codes) will be automatically generated
It is easier to read

Storing data from a select tag to a string using Javascript

I'm trying to take information out of a form controlled by a select statement and store it in a string. The plan is to send the information gathered from the user via email, which I used PHP to do. I have an idea how to do it (a while loop that's controlled by how many lines are in the list,) but I can't quite gather the information.
Here's the loop:
var empMessage = function(){
messageString = "";
var noEmp = $("#drpEmp option").length;
var i = 0;
$("#drpEmp").selector.index = i;
while (i < noEmp){
$("#drpEmp").index = i;
messageString = messageString +
"Name: " + firstName.val + " " + MI.val + " " + lastName.val + "<br/>" +
"Business: " + BusinessName.val + "<br/>" +
"Address: " + address.val + "<br/>" +
" " + city.val + ", " + state.val + " " + zip.val + "<br/>";
}
messageString = "<strong>Employee Information</strong><br/>" . messageString;
i++;
}
$("#stringHolder").val(messageString);
}
Here's the JS Fiddle:
https://jsfiddle.net/xptxz7by/3/
I know I probably really off. I know I have the loop working and the list is getting counted, but I can't seem to retrieve the information. I'm also thinking I'm approaching sending the information wrong and there's probably a better way of doing it, I just haven't figured out how.
The data you want is in the Employee object that you saved in each option's .data(), so you need to get that data and use the properties.
messageString = "<strong>Employee Information</strong><br/>";
$("drpEmp option:selected").each(function() {
var employee = $(this).data("employee");
messageString +=
"Name: " + employee.firstName + " " + employee.MI + " " + lastName + "<br/>" +
"Business: " + employee.BusinessName + "<br/>" +
"Address: " + employee.address + "<br/>" +
" " + employee.city + ", " + employee.state + " " + employee.zip + "<br/>";
});

jquery increase by 1

Afternoon,
I would like to increase the number in this code by 1 for each question displayed.
new_question = "<div id=\"" + res.qId + "\">" +
"<h1>Question 1</h1>" +
"<p><i>" + res.question + "</i></p>" +
"<div class=\"answer-grid\">" +
"<div id=\"a1\" class=\"answer\">" +
"<p>" + res.answer1 + "</p>" +
"<p>" + res.answer2 + "</p>" +
"<p>" + res.answer3 + "</p>" +
"</div>" +
"</div>";
With this it would show, question 1, question 2, and so on...
How would i go about doing this in jQuery please?
Update Victor provided what i needed, thanks all for your help. Updated code below.
var questionNumber = 1;
$.each(result, function (index, res) {
new_question = "<div id=\"" + res.qId + "\">" +
"<h1>Question " + (questionNumber++) + "</h1>" +
"<p><i>" + res.question + "</i></p>" +
"<div class=\"answer-grid\">" +
"<div id=\"a1\" class=\"answer\">" +
"<p>" + res.answer1 + "</p>" +
"<p>" + res.answer2 + "</p>" +
"<p>" + res.answer3 + "</p>" +
"</div>" +
"</div>";
$('#pinfos').append(new_question);
Declare a variable outside your loop and incremenet it inside your loop and use that in the markup.
var questionNumber=0;
$.each(someJsonData, function (index, res) {
{
questionNumber++;
new_question = "<div id=\"" + res.qId + "\">" +
"<h1>Question "+questionNumber+"</h1>" +
"<p><i>" + res.question + "</i></p>" +
"<div class=\"answer-grid\">" +
"<div id=\"a1\" class=\"answer\">" +
"<p>" + res.answer1 + "</p>" +
"<p>" + res.answer2 + "</p>" +
"<p>" + res.answer3 + "</p>" +
"</div>" +
"</div>";
}
Declare a var called questionNumber and increment it at each call
var questionNumber = 1;
$.each(result, function (index, res) {
new_question = "<div id=\"" + res.qId + "\">" +
"<h1>Question " + (questionNumber++) + "</h1>" +
"<p><i>" + res.question + "</i></p>" +
"<div class=\"answer-grid\">" +
"<div id=\"a1\" class=\"answer\">" +
"<p>" + res.answer1 + "</p>" +
"<p>" + res.answer2 + "</p>" +
"<p>" + res.answer3 + "</p>" +
"</div>" +
"</div>";
$('#pinfos').append(new_question);

Categories

Resources