I'm needing to style a table that's dynamically created by javascript. I know how to style it if it were just a static HTML table but this is different and I'm not too familiar with javascript. Here is the javascript code:
[var aryPortalList = \[\];
function getPortalList() {
var wP = window.location.protocol;
var wH = window.location.host;
var wPath = "ibi_apps/rs/ibfs/BIP/Portals?IBIRS_action=get";
//http://webfocusclidev:8080/ibi_apps/rs/ibfs/BIP/Portals?IBIRS_action=get;
var webfocusAPI = wP + "//" + wH + "/" + wPath;
$.ajax({
type: "GET",
async: false,
url: webfocusAPI,
dataType: 'xml',
success: function(xml) {
$(xml).find('children').children().each(function() {
var portal = { Name: $(this).attr('bipName'),
Link: "/ibi_apps/bip/portal" + $(this).attr('bipPath'),
IconLink: "/ibi_apps/WFServlet.ibfs?IBFS1_action=RUNFEX&IBFS_path=" + $(this).attr('bipIconPath')
}; //var portal
console.log("portal.name=" + portal.Name);
if (portal.Name != "GlobalBI") aryPortalList.push(portal);
}); //each
console.log("Portals in List = " + aryPortalList.length);
} //success function
}); //ajax
}
function displayPortalList_Icon() {
if (aryPortalList.length == 0) {
var hTxt = "<p>You do not have access to any portals</p>";
$("#portallist").append(hTxt);
} else {
var bRowAdded = false;
var hTbl=$("<table id='tbl_portallist'></table>");
var row = $('<tr></tr>').addClass('ingrPL_row');
console.log("Portals in List = " + aryPortalList.length);
for(var j=0; j < aryPortalList.length; j++) {
var cell = $("<td align = 'center'></td>");
var hTxt = $("<p>" + aryPortalList\[j\].Name + "</p>");
var hLink = $("<a>").attr({"href": aryPortalList\[j\].Link,
"target": "_blank"});
var img = $("<img>").attr("src", aryPortalList\[j\].IconLink);
img.width("100px");
img.height("100px");
console.log("hTxt=" + hTxt);
hLink.append(img);
cell.append(hTxt);
cell.append(hLink);
row.append(cell);
bRowAdded = false;
if ((j+1) % 4 == 0) {
hTbl.append(row);
bRowAdded = true;
var row = $('<tr></tr>').addClass('ingrPL_row');
}
}
if (!bRowAdded) {
hTbl.append(row);
}
$("#portallist").html(hTbl);
}
}
function displayPortalList_List() {
if (aryPortalList.length == 0) {
var hTxt = "<p>You do not have access to any portals</p>";
$("#portallist").append(hTxt);
} else {
var bRowAdded = false;
var hTbl=$("<table id='tbl_portallist'></table>");
console.log("Portals in List = " + aryPortalList.length);
for(var j=0; j < aryPortalList.length; j++) {
var row = $('<tr></tr>').addClass('ingrPL_row');
var cell = $("<td align = 'center'></td>");
var hTxt = $("<p>" + aryPortalList\[j\].Name + "</p>");
var hLink = $("<a>").attr({"href": aryPortalList\[j\].Link,
"target": "_blank"});
console.log("hTxt=" + hTxt);
hLink.append(hTxt);
cell.append(hLink);
row.append(cell);
hTbl.append(row);
}
$("#portallist").html(hTbl);
console.log("portal.name=" + portal.Name);
}
}][1]
And I've attached a photo of how the 'portal' looks.
What I need to do is space out the icons more and have the title's on the bottom of the icons, to look more like an 'iphone app'
Any help is greatly appreciated.
you can style it in the same way you style static elements
looking at your code I can see the table have an ID and the rows have classes
var hTbl=$("<table id='tbl_portallist'></table>");
var row = $('<tr></tr>').addClass('ingrPL_row');
so you can select those in your CSS file
CSS
#tbl_portallist {
/*table style here */
}
#tbl_portallist th {
/*table head style here*/
}
#tbl_portallist tr {
/*table row style here*/
}
#tbl_portallist td {
/*table data (cell) style here*/
}
Related
I have a function which makes an AJAX call and depending on the answer, sets the colour of an input. The function core itself works fine. However, when it comes to changing the colour of the input, it is not working.
function Nueva_Red() {
var e1 = document.getElementById("rrss_tipo");
var e2 = document.getElementById("rrss_usuario");
var e3 = document.getElementById("redes");
var e4 = document.getElementById("alta_nueva_red");
var id_red = e1.options[e1.selectedIndex].value;
var red = e1.options[e1.selectedIndex].text;
var usuario = e2.value;
e2.style.backgroundColor = "none";
e2.style.borderColor = "black";
if ((id_red > 0) && (usuario != "")) {
var datastr = 'seccion=rrss_check&dato=' + id_red + "|" + usuario;
$.ajax({
type: 'GET',
url: 'validacion.php',
data: datastr,
success: function(html) {
if (html == 1) {
document.getElementById("nuevas_rrss").style.visibility = "visible";
document.getElementById("nuevas_rrss").style.display = "inline-block";
var opcion = document.createElement("option");
opcion.value = id_red + "-" + usuario;
opcion.innerHTML = red + " -> " + usuario;
e3.appendChild(opcion);
e1.value = 0;
e2.value = "";
e2.title = "";
e2.style.backgroundColor = "none";
e2.style.borderColor = "black";
} else {
e2.title = html;
e2.style.backgroundColor = error_error;
e2.style.borderColor = error_error;
}
},
error: function(html) {
e2.style.borderColor = error_app;
e2.style.backgroundColor = error_app;
}
});
}
}
Thank you!
I have created an accordion with categories. I am pulling the content from a share point list with an ajax call. Each item on the share point list has its category assigned (automotive, entertainment, housing, etc). I need every item to be filtered by category.
https://jsfiddle.net/angelogianopulos/7L392emj/11/
$(document).ready(function() {
/*r container = document.createElement("div");
container.setAttribute('id', 'container');
container.classList.add('container', 'text-center', 'my-5');*/
$.ajax({
url: "http://bc-net/_api/web/lists/GetByTitle('specialDiscounts')/items",
method: "GET",
headers: {
"Accept": "application/json; odata=verbose"
},
success: function(data) {
var items = data.d.results;
console.log(items);
var createRows = function(i, items) {
//Creates 3 Rows inside container
var row = document.createElement("div");
row.setAttribute('id', 'row' + i);
row.classList.add('row', 'animated', 'fadeInUp');
//Appends Row to Container
var getContainer = document.getElementById('automotive');
getContainer.appendChild(row);
createColumns(i, items);
}; //End of creare Rows Function
//Creates columns
var createColumns = function(i, items) {
for (var j = i; j < (i + 3); j++) {
//Creates 3 Columns inside the 3 rows
var columns = document.createElement("div");
columns.setAttribute('id', 'columns' + j);
columns.classList.add('col-md-4');
//appends the 3 columns inside the rows
var getRow = document.getElementById('row' + i);
getRow.appendChild(columns);
//Create single News
var singleNews = document.createElement("div");
singleNews.setAttribute('id', 'singleNews' + j);
singleNews.classList.add("single-news", "mb-4");
var getColumns = document.getElementById('columns' + j);
getColumns.appendChild(singleNews);
//Inside Row
var insideRow = document.createElement("div");
insideRow.setAttribute('id', 'insideRow' + j);
insideRow.classList.add('row');
var getsingleNews = document.getElementById('singleNews' + j);
getsingleNews.appendChild(insideRow);
//Col-md-3
var insideCol = document.createElement("div");
insideCol.setAttribute('id', 'insideCol' + j);
insideCol.classList.add('col-md-3');
//Col-md-9
var insideColRight = document.createElement("div");
insideColRight.setAttribute('id', 'insideColRight' + j);
insideColRight.classList.add('col-md-9');
var getInsideRow = document.getElementById('insideRow' + j);
getInsideRow.appendChild(insideCol);
getInsideRow.appendChild(insideColRight);
//Rounded Image Class
var rounded = document.createElement("div");
rounded.setAttribute('id', 'rounded' + j);
rounded.classList.add('rounded', 'z-depth-1', 'mb-4');
var getinsideCol = document.getElementById('insideCol' + j);
getinsideCol.appendChild(rounded);
//Pulls the images from the list
var image = document.createElement("img");
image.setAttribute('id', 'image' + j);
image.classList.add("img-fluid");
image.src = items[j].Image.Url;
var getRounded = document.getElementById('rounded' + j);
getRounded.appendChild(image);
//Pulls header from the list
var title = document.createElement("p");
title.setAttribute('id', 'title' + j);
title.innerHTML = items[j].Title;
title.classList.add("font-weight-bold", "dark-grey-text");
insideColRight.appendChild(title);
var justifyContent = document.createElement('div');
justifyContent.setAttribute('id', 'justifyContent' + j);
justifyContent.classList.add('d-flex', 'justify-content-between', 'topSpace');
insideColRight.appendChild(justifyContent);
var textTruncate = document.createElement('div');
textTruncate.setAttribute('id', 'textTruncate' + j);
textTruncate.classList.add('col-11', 'text-truncate', 'pl-0', 'mb-3');
justifyContent.appendChild(textTruncate);
//Pulls anchor from the list
var anchor = document.createElement("a");
anchor.setAttribute('id', 'anchor' + j);
anchor.setAttribute('href', items[j].Link.Url, +j);
anchor.setAttribute('target', '_blank', +j);
anchor.classList.add("dark-grey-text");
anchor.innerHTML = items[j].Description;
textTruncate.appendChild(anchor);
var arrowAnchor = document.createElement("a");
arrowAnchor.setAttribute('id', 'arrowAnchor' + j);
arrowAnchor.setAttribute('target', '_blank' + j);
arrowAnchor.setAttribute('href', items[j].Link.Url, +j);
justifyContent.appendChild(arrowAnchor);
var iconArrow = document.createElement('i');
iconArrow.classList.add('fas', 'fa-angle-double-right');
var getarrowAnchor = document.getElementById('arrowAnchor' + j);
getarrowAnchor.appendChild(iconArrow);
//var test = document.getElementById( 'arrowAnchor' + j);
//test.onclick = function() {
// console.log('Hello');
//}
} //End of j Loop
return;
} // End of createColumns function
//Array of categories
var catGroup = [];
console.log(catGroup);
if (items.length > 0) {
for (var i = 0; i < items.length; i++) {
var categories = items[i].Category;
console.log(categories)
catGroup.push(categories);
if (catGroup[i] === "Automotive") {
var automotive = document.getElementById('automotive');
console.log(catGroup[i]);
}
if (catGroup[i] === "Entertainment") {
var entertainment = document.getElementById('entertainment');
console.log(catGroup[i]);
}
if (catGroup[i] === "Health and Beauty") {
var health = document.getElementById('health');
console.log(catGroup[i]);
}
if (catGroup[i] === "Travel") {
var travel = document.getElementById('travel');
console.log(catGroup[i]);
}
if (catGroup[i] === "Electronics") {
var electronics = document.getElementById('electronics');
console.log(catGroup[i]);
}
if (catGroup[i] === "Services") {
var services = document.getElementById('services');
console.log(catGroup[i]);
}
if (catGroup[i] === "Housing") {
var housing = document.getElementById('housing');
console.log(catGroup[i]);
} else {}
if (i % 3 == 0) {
createRows(i, items);
} //end of % if statement
} //End of for loop
} //End of if item.length statement
},
error: function(data) {
alert("Error: " + data);
}
}); //End Service Icons //End Service Icons
}); //End ready function
I expect every item to be placed by category in its own content panelenter image description here
After looking into your question, what I understood is you just want to filter your data on the basis of 'category assigned'.
I will refer you to use JavaScript Filter like so:
const result = items.filter(Category => Category === "Automotive" );
Or, if you can use Lodash, there are a lot of ways to filter and even you can group by the Category.
You can check out here for Lodash:
Documentation Lodash
If I misunderstood your question, please let me know so I can edit my answer.
I am trying to remove any duplicate players that show up in search, when you search using an API. The player will stay on the table when the new search begins, however, certain APIs have multiple duplicates of the same player. What would be the best way to to hide and check to see if there is another player that is a duplicate?
Thank you
function playerseachMSF() {
var searchPlayerFN = $("#searchFN").val().trim();
var searchPlayerLN = $("#searchLN").val().trim();
var searchedPlayer = "";
//allows user to only search for last name and have fist name be optional
if (searchPlayerFN == 0) {
var searchedPlayer = searchPlayerLN;
} else {
var searchedPlayer = searchPlayerFN + "-" + searchPlayerLN;
}
var playerQueryURL = "https://api.mysportsfeeds.com/v1.1/pull/nfl/2017-regular/active_players.json?" + "player=" + searchedPlayer;
$.ajax({
type: "GET",
url: playerQueryURL,
dataType: 'json',
async: true,
headers: {
"Authorization": "Basic " + btoa("chen" + ":" + "testing")
},
}).done(function(response) {
console.log("PlayerSearch MSF - " + playerQueryURL);
var playerResults = response.activeplayers.playerentry;
for (var i = 0; i < playerResults.length; i++) {
//removes any variables with undifined results
if (playerResults[i].team !== undefined) {
var playerResults_FN = playerResults[i].player.FirstName;
var playerResults_LN = playerResults[i].player.LastName;
var playerResults_Position = playerResults[i].player.Position;
var playerResults_Team = playerResults[i].team.Name;
var playerResults_City = playerResults[i].team.City;
var playerResults_CityAbbr = playerResults[i].team.Abbreviation;
var playerResults_IMG = playerResults[i].player.officialImageSrc;
}
if (playerResults[i].player.externalMapping !== null) {
var playerResults_ID = playerResults[i].player.externalMapping.ID;
}
//adds players that match searched name to table
$("#tableSearchList")
.append($("<tr>")
.attr("id", playerResults_ID)
.attr("data-FN", playerResults_FN)
.attr("data-LN", playerResults_LN)
.attr("class", "players")
.append( $("<td>").text(playerResults_FN + " " + playerResults_LN))
.append( $("<td>").text(playerResults_Team))
.append( $("<td>").text(playerResults_Position))
) //<tr> append
} //for loop
// on click for when a player is selected
$(".players").on("click", function() {
$("#resultsBox").show();
$("#searchPanel").hide(1000);
var playerID = $(this).attr("id");
var playerFN = $(this).attr("data-FN");
var playerLN = $(this).attr("data-LN");
arrestRecord(playerFN, playerLN);
playerDisplay(playerID);
displayPlayerStats(playerFN, playerLN);
playerFantasyStats(playerFN, playerLN)
})
You can check to see if the table already contains a row with the player's id before adding the new row.
if ($('#' + playerResults_ID).length === 0) {
$("#tableSearchList")
.append($("<tr>")
.attr("id", playerResults_ID)
.attr("data-FN", playerResults_FN)
.attr("data-LN", playerResults_LN)
.attr("class", "players")
.append( $("<td>").text(playerResults_FN + " " + playerResults_LN))
.append( $("<td>").text(playerResults_Team))
.append( $("<td>").text(playerResults_Position))
) //<tr> append
}
//else, player id already exists
add an array of existing players and compare to that before you add a new one.
function playerseachMSF() {
var searchPlayerFN = $("#searchFN").val().trim();
var searchPlayerLN = $("#searchLN").val().trim();
var searchedPlayer = "";
var alreadyPlaying = []
//allows user to only search for last name and have fist name be optional
if (searchPlayerFN == 0) {
var searchedPlayer = searchPlayerLN;
} else {
var searchedPlayer = searchPlayerFN + "-" + searchPlayerLN;
}
var playerQueryURL = "https://api.mysportsfeeds.com/v1.1/pull/nfl/2017-regular/active_players.json?" + "player=" + searchedPlayer;
$.ajax({
type: "GET",
url: playerQueryURL,
dataType: 'json',
async: true,
headers: {
"Authorization": "Basic " + btoa("chen" + ":" + "testing")
},
}).done(function(response) {
console.log("PlayerSearch MSF - " + playerQueryURL);
var playerResults = response.activeplayers.playerentry;
for (var i = 0; i < playerResults.length; i++) {
//removes any variables with undifined results
if (playerResults[i].team !== undefined) {
var playerResults_FN = playerResults[i].player.FirstName;
var playerResults_LN = playerResults[i].player.LastName;
var playerResults_Position = playerResults[i].player.Position;
var playerResults_Team = playerResults[i].team.Name;
var playerResults_City = playerResults[i].team.City;
var playerResults_CityAbbr = playerResults[i].team.Abbreviation;
var playerResults_IMG = playerResults[i].player.officialImageSrc;
}
if (playerResults[i].player.externalMapping !== null) {
var playerResults_ID = playerResults[i].player.externalMapping.ID;
}
if(alreadyPlaying.indexOf(playerResults_ID) == -1) {
alreadyPlaying.append(playerResults_ID)
//adds players that match searched name to table
$("#tableSearchList")
.append($("<tr>")
.attr("id", playerResults_ID)
.attr("data-FN", playerResults_FN)
.attr("data-LN", playerResults_LN)
.attr("class", "players")
.append( $("<td>").text(playerResults_FN + " " + playerResults_LN))
.append( $("<td>").text(playerResults_Team))
.append( $("<td>").text(playerResults_Position))
) //<tr> append
}
} //for loop
// on click for when a player is selected
$(".players").on("click", function() {
$("#resultsBox").show();
$("#searchPanel").hide(1000);
var playerID = $(this).attr("id");
var playerFN = $(this).attr("data-FN");
var playerLN = $(this).attr("data-LN");
arrestRecord(playerFN, playerLN);
playerDisplay(playerID);
displayPlayerStats(playerFN, playerLN);
playerFantasyStats(playerFN, playerLN)
})
This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 7 years ago.
I've been building an app in jQuery and html 5 that reads rss feed of a blog. I wanted to show a list of titles of rss and when user clicks on the title it goes to a different page where full content is shown. I could get content using ajax and store them in an array. But when I'm clicking on the title, it shows undefined on the next page. I am using jQuery pages.
$(document).ready(function() {
load_posts();
});
function load_posts() {
var PAGINATION = $('#pagination');
var HTML1 = '<li><a href="#post" data-transition="slide" id ="';
var HTML5 = '"><h4>';
var HTML2 = '</h4>';
var HTML3 = '<p>';
var HTML4 = '</p></a></li>';
var btn = "";
var selector = "";
var i = 0;
var title = "";
var pubDate = "";
var dascription = "";
var anchorID = "";
var url = "";
var fullPost = new Array;
var link = new Array;
$.ajax({
type: 'GET',
url: 'http://smushbits.com/feed/',
dataType: 'xml',
error: function() {
alert("An error occured!");
},
success: function(xml) {
$(xml).find('item').each(function() {
title = $(this).find('title').text();
pubDate = $(this).find('pubDate').text();
pubDate = pubDate.substring(5, 16);
description = $(this).find('encoded').text();
url = $(this).find('link').text();
fullPost.push(description);
link.push(url);
anchorID = "btn" + i.toString();
$(HTML1 + anchorID + HTML5 + title + HTML2 + HTML3 + pubDate + HTML4).appendTo(PAGINATION);
i = i + 1;
});
for (var j = 0; j < fullPost.length; j++) {
btn = "#btn" + j.toString();
selector = $(btn);
$(document).on("click", selector, function() {
document.getElementById('entry').innerHTML = fullPost[j];
});
}
PAGINATION.listview("refresh");
}
});
}
It is the infamous for loop issue.
for (var j = 0; j < fullPost.length; j++) {
(function(j) {
var btn = "#btn" + j;
$(document).on("click", btn, function() {
document.getElementById('entry').innerHTML = fullPost[j];
});
}(j));
}
I am currently making an autocomplete function that retrieves a bunch of information encoded by JSON and allows the user to search through it. There is a slight delay in the search results, and I think that a for loop inside of another for loop is the cause of this issue. Below is the Javascript file:
var username = [];
var businessname = [];
var fname = [];
var lname = [];
var fullname = [];
var clientid = [];
var bankArray = [];
var data_for_post = [];
var focusedArrayElement = "";
var started = false;
var currentSelectedList = 0;
var searchString = "";
$(document).keydown(function(event) {
switch(event.keyCode) {
case 40:
if (!$("#results li:first").hasClass("selected") && !started) {
$("#results li:first").addClass("selected");
started = true;
} else {
if($("#results li.selected").next().length > 0) {
$("#results li.selected").next().addClass("selected");
$("#results li.selected:first").removeClass("selected");
}
}
assign = $(".selected").text();
$(".autocomplete").val(assign);
break;
case 38:
$("#results li.selected").prev().addClass("selected");
$("#results li.selected:last").removeClass("selected");
if(!$("#results").siblings('.selected').length > 0) {
started = false;
}
assign = $(".selected").text();
$(".autocomplete").val(assign);
break;
case 13:
assign = $(".selected").text();
console.log(assign);
$("#results").empty();
$("#inner").text(assign);
break;
}
});
$(document).ready(function() {
$.ajax({
type: "GET",
dataType: "json",
url: "autocomplete.php?search=1",
success: function(data) {
$.each(data.client, function(key, value) {
username.push(value.username);
businessname.push(value.businessname);
fname.push(value.fname);
lname.push(value.lname);
clientid.push(value.clientid);
for(var i = 0; i < fname.length; i++) {
fullname[i] = fname[i] + " " + lname[i];
}
});
bankArray = [username, businessname, fullname, clientid];
console.log(bankArray);
}
});
$(".autocomplete").on("keyup change", function(e) {
console.log(e.keyCode);
if(e.keyCode != 38 && e.keyCode != 40) {
$("#results").empty();
}
currentSearchString = $(".autocomplete").val();
if(currentSearchString) {
//$("#results").css('border-top', '1px solid black');
for(var i = 0; i < bankArray.length; i++) {
for(var j = 0; j < bankArray[i].length; j++) {
focusedArrayElement = bankArray[i][j].toLowerCase();
usernames = bankArray[0];
businessnames = bankArray[2];
fullnames = bankArray[3];
if(focusedArrayElement.indexOf(currentSearchString.toLowerCase()) > -1) {
focused_businessname = bankArray[1][j];
focused_fullname = bankArray[2][j];
focused_clientid = bankArray[3][j];
postedData = focused_fullname + " -- " + focused_businessname;
if (!$(".clientid." + focused_clientid).length) {
$("#results").append("<li id='" + (j + 1) + "' class='clientid " + focused_clientid + "'>" + postedData + "</li>");
}
}
}
}
}
else {
$("#results").empty();
started = false;
}
});
});
The basic principle is that when the document readies, an ajax call pushes all of the JSON data into a multidimensional array with different categories of information. From here, a first for loop searches through each array in the bankArray, and the second searches through each element of the current array. If the current search string in the input field matches the focused element from the array, it appends that information to a div below.
I feel as if the code is inefficient in how it deals with the JSON data and checks through it. If anyone has any suggestions on how to optimize the code, that would be great.