Getting a sub-class out of an array - javascript

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

Related

MVC Java script loop async controller data

I'm running a script and want to output an alert when it is finished loading all data.
The problem is, I have a for loop and call a MVC controller function,
but the alert is outputted/triggered bevor the data is loaded completely.
It seems like the data fetching from the controller runs asynchronously.
I added the async and await but it changed nothing.
Script:
async function checkform() {
$("#faRueckmeldungen").html("")
let _clipboard="";
var _fanr = $('#FaNr').val();
var _faArray = _fanr.replace(/\n/g, " ").split(" ");
for (var i = 0; i <= _faArray.length; i++) {
var _fA = _faArray[i];
if (_fA < 2013810000) {
(document.getElementById("FaNr")).style.backgroundColor = "OrangeRed";
alert("FaNr #" + _fA + " nicht korrekt!");
}
else {
var url = "/FaInfos/FaRueckmeldung";
$.get(url, { faNr: _fA }, await function (data) {
$("#faRueckmeldungen").append(data[0]);
_clipboard += data[1];
navigator.clipboard.writeText(_clipboard);
})
}
}
alert("finished")
}
Controller function:
public JsonResult FaRueckmeldung(string faNr)
{
if (faNr == null)
return null;
//Loading data from SAP
var faHead = SapInterClient.GetFaHead(faNr.ToString());
var faPos = SapInterClient.GetFaPos(faNr.ToString());
//<td>"++"</td>
string clippoard = "Fertigungsauftrag\tMaterialnummer\tAuftragsmenge\tStart Termin Soll\tStart Termin Ist\tEndtermin Soll\tEndtermin Ist\tPersonal Soll [min]\tPersonal Ist [min]";
string sret = "<table class=" + (char)34 + "table1" + (char)34 + #"><thead><tr>
<th>Fertigungsauftrag</th>
<th>Materialnummer</th>
<th>Auftragsmenge</th>
<th>Start Termin Soll</th>
<th>Start Termin Ist</th>
<th>Endtermin Soll</th>
<th>Endtermin Ist</th>
<th>Personal Soll [h]</th>
<th>Personal Ist [h]</th>";
decimal VgPers = 0;
decimal RuPers = 0;
for (int i = 0; i < faPos.RückgemeldeteLeistungRP.Count(); i++)
{
VgPers += faPos.RückgemeldeteLeistungTP[i];//VorgabePersonal
RuPers += faPos.RückgemeldeteLeistungRP[i];//FeedbackPersonal
}
string cellColor = "LightGreen";
if (VgPers/60 < RuPers)
cellColor = "Salmon";
foreach (var item in faPos.Vorgangsnummer)
{
clippoard += "\t VG " + item;
sret += "<th> VG " + item + "</th>";
}
clippoard += "\r\n";
sret += "</tr></thead>";
sret += "<tr><td>" + faNr + "</td><td>" + faHead.MatNr + "</td><td>" + faHead.GesamteAuftragsmenge + "</td><td>" + faHead.TerminierterStart.ToString("dd.MM.yyyy") + "</td><td>" + faHead.IstStartTermin.ToString("dd.MM.yyyy") + "</td><td>" + faHead.TerminiertesEnde.ToString("dd.MM.yyyy") + "</td><td>" + faHead.IstEndTermin.ToString("dd.MM.yyyy") + "</td><td>" + String.Format("{0:0.00}", VgPers / 60) + "</td><td bgcolor=" + (char)34 + cellColor + (char)34 + ">" + String.Format("{0:0.00}", RuPers) + "</td>";
clippoard += faNr + "\t" + faHead.MatNr + "\t" + faHead.GesamteAuftragsmenge + "\t" + faHead.TerminierterStart.ToString("dd.MM.yyyy") + "\t" + faHead.IstStartTermin.ToString("dd.MM.yyyy") + "\t" + faHead.TerminiertesEnde.ToString("dd.MM.yyyy") + "\t" + faHead.IstEndTermin.ToString("dd.MM.yyyy") + "\t" + String.Format("{0:0.00}", VgPers / 60) + "\t" + String.Format("{0:0.00}", RuPers);
for (int i = 0; i < faPos.GutmengeGesamt.Count(); i++)
{
clippoard += "\t" + faPos.GutmengeGesamt[i];
sret += "<td>" + faPos.GutmengeGesamt[i] + "</td>";
}
clippoard += "\r\n";
sret += "</tr></table>";
return Json(new List<string>{sret,clippoard}, JsonRequestBehavior.AllowGet);
}
Please help.
Best regards Simon
You forgot to add await before the $.get(url....). The await before function has no reason to be there. Add async if you make asynchronous calls in there, though I do not see any.
The idea is that you add await to the specific instruction that works asynchronously ( and you want to wait for it). In your case, your callback function that you send to get is not the async function, rather the .get() itself is the guy you're looking for. The callback function you send there is being executed after the api call is done, and it's handled by .get() itself.
So your code will look a little something like this:
await $.get(
url,
{ faNr: _fA },
function (data) {
$("#faRueckmeldungen").append(data[0]);
_clipboard += data[1];
navigator.clipboard.writeText(_clipboard);
}
)

Can this be turned into a for loop?

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');

array for loop, looping too many times javascript

Instead of looping through one time to show
id1
id2
id3
it loops through 3 times before stopping. what can i put to make it loop through only once.
html:
<p id="show_me"></p>
<button onclick="ObjectArray()">click me</button>
javascript:
var ObjectArray = function() {
// object literal
var id1 = {
firstName: "John",
lastName: "Doe",
id: "12345"
};
// keyword new
var id2 = new Object;
id2.firstName = "Adam";
id2.lastName = "Bakely";
id2.id = "abcdef";
// object constructor
function employee(first, last, id) {
this.firstName = first;
this.lastName = last;
this.id = id;
}
var id3 = new employee("Dallas", "Star", "abc123");
//create an array
var IdArray = [id1, id2, id3];
//for loop to display results
var text="";
var i;
for (i = 0; i < IdArray.length; i++){
text += IdArray[0].firstName + " " + IdArray[0].lastName + " " + IdArray[0].id + "<br>";
text += IdArray[1].firstName + " " + IdArray[1].lastName + " " + IdArray[1].id + "<br>";
text += IdArray[2].firstName + " " + IdArray[2].lastName + " " + IdArray[2].id + "<br>";
}
document.getElementById("show_me").innerHTML = text;
}
It iterates three times, because you loop for the length of the array, which has 3 items.
If you want to 'iterate' once, you can just omit the for loop:
text += IdArray[0].firstName + " " + IdArray[0].lastName + " " + IdArray[0].id + "<br>";
text += IdArray[1].firstName + " " + IdArray[1].lastName + " " + IdArray[1].id + "<br>";
text += IdArray[2].firstName + " " + IdArray[2].lastName + " " + IdArray[2].id + "<br>";
But I think you actually wanted to do this:
for (i = 0; i < IdArray.length; i++){
text += IdArray[i].firstName + " " + IdArray[i].lastName + " " + IdArray[i].id + "<br>";
}
That way you use the loop what it's for: Iterate over an array of any length and repeat a piece of code for each item in the array.
Remove everything from the for loop, and add this instead:
text += IdArray[i].firstName + " " + IdArray[i].lastName + " " + IdArray[i].id + "<br>";
Every thing is fine ... but please replaced the following code
for (i = 0; i < IdArray.length; i++){
text += IdArray[i].firstName + " " + IdArray[i].lastName + " " + IdArray[i].id + "<br>";
text += IdArray[1].firstName + " " + IdArray[1].lastName + " " + IdArray[1].id + "<br>";
text += IdArray[2].firstName + " " + IdArray[2].lastName + " " + IdArray[2].id + "<br>";
}
with
for (i = 0; i < IdArray.length; i++){
text += IdArray[i].firstName + " " + IdArray[i].lastName + " " + IdArray[i].id + "<br>";
}

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/>";
});

How to pass Jquery value to code behind in asp.net

$("#getButtonValue").click(function () {
var msg = '';
for (i = 1; i < counter; i++) {
msg += "\n Width #" + i + " : " + $('#txtWidth' + i).val();
msg += "\n Height #" + i + " : " + $('#txtHeight' + i).val();
msg += "\n Length #" + i + " : " + $('#txtLength' + i).val();
msg += "\n Weight #" + i + " : " + $('#txtWeight' + i).val();
}
alert(msg);
});
This code return height,width,length and weight multiple time (With respect to conter).
I want to pass All this value to code behind file .And pass all value to this packeges.
qurystr += "&packages[1][width]=" ";
qurystr += "&packages[1][height]="";
qurystr += "&packages[1][length]="";
qurystr += "&packages[1][weight]="";
Please help.Thanks
You can Use Hidden Fields to Save your List as Comma Separated Values
<asp:HiddenField runat="server" id="hdf" />
In JS
$('<%#hdf.CliendID%>').value="1,2,3,4,5,6,7,8,9";
width,height,length,width,height,length....

Categories

Resources