How can I use each loop variable (item) outside of loop - javascript

I want to make a switch for declaring variables inside each loop, like this
switch (label) {
case "Users":
content = item.username+ ' ' + item.firstname + ' '
+ item.lastname + '('+ item.organization + ')';
break;
default:
}
$.each(result, function (i, item) {
html += "<option value ='" + item.id + "'>" + content + "</option>";
});
But since item variable hasn't defined yet I will get an ReferenceError.
Moving switch inside loop will make It really slow.
Is this even possible to declare loop variables outside of scope?
function selectorAddEdit(label, tag, result, labelconf) {
var idtag = tag+"s";
var none = "<option value='None'>None</option>";
var labelHead = (labelconf=="head") ? "<div class='selectTitles'><label>"+label+"</label></div>" : "";
switch (label) {
case "Users":
var content = item.username + ' ' + item.firstname + ' ' + item.lastname + '('+ item.organization + ')';
break;
default:
}
var html = labelHead + "<select name='" + tag + "' class='" + tag + "'>";
$.each(result, function (i, item) {
html += "<option value ='" + item.id + "'>" + content + "</option>";
});
html += "</select></div>";
$("." + idtag).html(html);
}

Declare the content as a global variable
var content="";
switch (label) {
case "Users":
content = item.username+ ' ' + item.firstname + ' ' + item.lastname + '('+ item.organization + ')';
break;
default:
}
$.each(result, function (i, item) {
html += "<option value ='"+item.id+"'>"+content+"</option>";
});

This is assuming that item is distinct/unique and therefore you want the switch statement to be re-evaluated at each iteration of loop. What you can do is to use a method/function that returns the value, after evaluating a given condition:
var getOptionContent = function(item) {
switch (label) {
case "Users":
return item.username + ' ' + item.firstname + ' ' + item.lastname + '(' + item.organization + ')';
default:
return '';
}
}
var html = labelHead + "<select name='" + tag + "' class='" + tag + "'>";
$.each(result, function(i, item) {
html += "<option value ='" + item.id + "'>" + getOptionContent(item) + "</option>";
});

Related

give multiple params for a tag onclick function in JSP

I use a tag onclick function to delete specific documents.
I call the function with three arguments.
but my regex does not include a specific case.
Generally, it works, like "test".
but some case doen't work.
Like this case => "St. John's"
//return '<tr><td>' + key + '</td><td>' + value + '</td><td>' + '<a href="javascript:void(0);" onclick="deleteName(\'' + key + '\'' + ',\'' + value + '\'' + ',\'' + regionCode + '\');" >[ 삭제 ]</a>' + '</td></tr>';
//return '<tr><td>' + key + '</td><td>' + value + '</td><td>' + '<a href="javascript:void(0);" onclick="deleteName(\'' + key + '\'' + ',\'' + '/\"'+ value + '\'' + '\"/ ' + ',\'' + regionCode + '\');" >[ 삭제 ]</a>' + '</td></tr>';
const itemsArray = tableData.map(function(item) {
var key = Object.keys(item)[0];
var value = Object.values(item);
//return '<tr><td>' + key + '</td><td>' + value + '</td><td>' + '<a href="javascript:void(0);" onclick="deleteName(\'' + key + '\'' + ',\'' + value + '\'' + ',\'' + regionCode + '\');" >[ 삭제 ]</a>' + '</td></tr>';
//return '<tr><td>' + key + '</td><td>' + value + '</td><td>' + '<a href="javascript:void(0);" onclick="deleteName(\'' + key + '\'' + ',\'' + '/\"'+ value + '\'' + '\"/ ' + ',\'' + regionCode + '\');" >[ 삭제 ]</a>' + '</td></tr>';
return '<tr><td>' + key + '</td><td>' + value + '</td><td>' + '<a href="javascript:void(0);" onclick="deleteName(\'' + key + '\'' + ',\'' + "\"" + value + "\"" + ',\'' + regionCode + '\');" >[ 삭제 ]</a>' + '</td></tr>';
});
this is expected key value example
const key = "en";
const value = "test"; // it works
const value = "St. John's"; // it doesn't work.
const regionCode = "AG-ANU";
if onclick function call success,
it calls this function
function deleteName(key, value, regionCode) {
$.ajax({
url: "http://localhost:8080/api/v1/regions/" + regionCode + "/names?lang=" + key + "&name=" + value,
method: "DELETE",
success: function() {
alert("삭제되었습니다.");
location.reload();
},
error: function(err) {
console.log(err);
}
});
}
I need help for value part regex expression.
It is not good way, but I solved like this.
const itemsArray = tableData.map(function(item) {
var key = Object.keys(item)[0];
var value = Object.values(item)[0];
var valueStr = JSON.stringify(value);
var valueString = value.replace(/'/gi, "\\\'");
var keyValueRegionCode = key + "|" + valueString + "|" + regionCode;
return '<tr><td>' + key + '</td><td>' + value + '</td><td>' + '[ 삭제 ]' + '</td></tr>';
});
then calls keyValueRegionCode
function deleteName(keyValueRegionCode) {
var keyValue = keyValueRegionCode.split("|")[0];
var nameValue = keyValueRegionCode.split("|")[1];
var regionCode = keyValueRegionCode.split("|")[2];
$.ajax({
url: "http://localhost:8080/api/v1/regions/" + regionCode + "/names?lang=" + keyValue + "&name=" + encodeURIComponent(nameValue),
method: "DELETE",
success: function() {
alert("삭제되었습니다.");
location.reload();
},
error: function(err) {
console.log(err);
}
});
}
1) value.replace(/'/gi, "\\'"); -> this regex makes single apostrophe like this. (\')
2) make parameters one for calling function easily .

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(""));

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

Passing JQuery Arrays to Nested Function

I'm having problems with dynamically adding a row to a table using data stored in two arrays (categories and treatments). The arrays are fine, I've determined that.
When passing just the categories array the new row displays but the select box reads [object:object], it's clearly blank.
When I pass a second array with it, as shown below, the console reads 'undefined is not a function'.
Any help would be hugely appreciated!
// Add an extra row when button is clicked
var counter = 1;
$('input.add').click(categories, treatments, function(){
counter++;
var newRow = '<tr><td><label for="category' + counter + '">Category</label></td><td><select id="category' + counter + '" name="category' + counter + '" required="required">';
$.each(categories, function(key, value) {
$('#category' + counter)
newRow += '<option value ="' + key + '">' + value + '</option>';
});
newRow += '</select></td><td><label for="treatment' + counter + '">Treatment</label></td><td><select id="treatment' + counter + '" name="treatment' + counter + '">';
$.each(treatments, function(key, value) {
$('#treatment' + counter)
newRow += '<option value ="' + key + '">' + value + '</option>';
});
newRow += '</select></td></tr>';
$('table.treatments').append(newRow);
});
});
The first parameter for the jQuery .click() is an Object, and you're trying to pass two arrays.
This should work for you (remember to check for the missing semi-colons):
// Create an Object obj containing the two arrays.
$('input.add').click(obj = { categories: categories, treatments: treatments }, function () {
counter++;
var newRow = '<tr><td><label for="category' + counter + '">Category</label></td><td><select id="category' + counter + '" name="category' + counter + '" required="required">';
// Use the obj.
$.each(obj.categories, function (key, value) {
$('#category' + counter);
newRow += '<option value ="' + key + '">' + value + '</option>';
});
newRow += '</select></td><td><label for="treatment' + counter + '">Treatment</label></td><td><select id="treatment' + counter + '" name="treatment' + counter + '">';
// Use the obj.
$.each(obj.treatments, function (key, value) {
$('#treatment' + counter);
newRow += '<option value ="' + key + '">' + value + '</option>';
});
newRow += '</select></td></tr>';
$('table.treatments').append(newRow);
});
Demo
jQuery .click()

How do you pass json data from one page to another to reference the same row of data?

I am pulling address location information from a google spreadsheet and using it to create buttons. When you click on a button it then should open and populate the data for that location in a new page or if need into a dialog box.
How do you pass the information to a new page and complete the if statement? Everything works great if I manually add the entry.id.$t string in the last if statement.
$(document).ready(function () {
$(function FISLocations() {
$.getJSON("https://spreadsheets.google.com/feeds/list/GoogleSpreadsheetKey/od6/public/values? alt=json-in-script&callback=?",
function (data) {
$('.loc').append('<ul class="collapsibleList" id="list"><li><label for="mylist-node1" class="css_btn_classlist">Alabama</label><input type="checkbox" id="mylist-node1" /><ul class="loclist"></ul></li></ul>');
$.each(data.feed.entry, function (i, entry) {
var item = '<span style="display:none ">' + entry.id.$t + '</span>';
item += ' ' + entry.gsx$cityst.$t;
if (entry.gsx$state.$t == "AL") {
$('.loclist').append('<li>' + item + '</li>');
};
});
$('.poploc').append('<div class="items"></div>');
$.each(data.feed.entry, function (i, entry) {
var itemp = '<span style="display:none ">' + entry.id.$t + '</span>';
itemp += '' + entry.gsx$address1.$t + '<br/>';
itemp += ' ' + entry.gsx$city.$t + ', ';
itemp += ' ' + entry.gsx$state.$t;
itemp += ' ' + entry.gsx$postal.$t + '<br/>';
itemp += ' ' + entry.gsx$phone.$t + '<br/>';
itemp += ' ' + entry.gsx$fax.$t + '<br/>';
itemp += '<div class="px12bold"> ' + entry.gsx$email.$t + '<br/ ></div>';
itemp += '<div class="locmid"><br/><a ' + entry.gsx$androidloc.$t + 'class="css_btn_classsmall noselect">Map Us</a>';
itemp += ' Email Us ';
itemp += ' Call us </div>';
if (entry.id.$t == ? ? ? ? ? ? ) {
$('.items').append('<br>' + itemp + '</span><br/>');
};
});
});
});
});

Categories

Resources