The script below will loop through and generate 50 records. I have a dynamic value RANKS = "8". How can I check if 8 is exists in id="rankN"?
The value[RANKS] is dynamic from 1-50
var RANKS = "8";
var ranking;
for (var i = 0; i < rankingList.length; i++) {
var a = 1;
ranking = "<div > " +
("<div id=rank" + a + " class='RankCol'>" + rankingList[i].rankNo + "</div>") +
("<div>" + rankingList[i].username + "</div>") +
("<div>" + rankingList[i].winningAmt + "</div>") +
("<div> " + rankingList[i].uCoin + "</div>") +
(" </div>");
};
Expected result:
A
A
B
B
C
B
A
A
B
G
so if my ranking is 8, the text will bold. IF the value is not within 50, then i will do another css. my main problem is how can i check whether the looped' ID contains the id number same as my RANKS(which is 8)
If you want to check in DOM, then simply var exists = $('#rank8').length !== 0.
If you want it to check inside loop:
var ranks = {};
for (var i = 0; i < rankingList.length; i++) {
newRank = 'rank' + i;
if (typeof ranks[newRank] !== 'undefined') {
// skip
continue;
} else {
ranking = '<div id="' + newRank + '" ...';
}
ranks[newRank] = newRank;
}
Try this
rankingDiv.html(rankingList.map((rank,i) => `<div>
<div id="rank${i+1)" class='RankCol'>${rank.rankNo}</div>
<div>${rank.username}</div>
<div>${rank.winningAmt}</div>
<div>${rank.uCoin}</div>
</div>`);
const $myRank = $(`#rank${RANKS}`);
if ($myRank.length===1) myRank.html(`<b>${$myRank.text()}</b>`)
Older sugggestion
$(\`#rank${RANKS}\`).length===1
Related
I am trying to the splice method but it is not working properly want to delete one user but it is deleting 2.
Also want to add the binary search button
this is the requirement for binary search
Replace the sequential access algorithm to operate on the arrays with a binary search algorithm.
To implement this, the array’s data must be sorted. You may refer to an online example available at Array.prototype.sort() to learn about sorting data in arrays.
function Display_Athlete() {
var text = "<hr/>";
for (let i = 0; i < athlete_name.length; i++) {
text += "Athlete No - " + (i + 1) + ", Athlete Name is " + athlete_name[i]
+ " and height is " + athlete_height[i] + "<br>";
}
document.getElementById("message").innerHTML = text;
}
//Created function to remove the user
function Remove_Athlete() {
var person = prompt("Enter the name to remove the Athlete");
for (let i = 0; i < athlete_name.length; i++) {
athlete_name.splice(person - 1, 1);
athlete_height.splice(person - 1, 1);
alert(" Athlete_name " + athlete_name + " Athlete_height " + athlete_height + " is removed ");
}
}
//Create the function to find the user
function Find_Athlete() {
var person = prompt("Enter the name to Find the Athlete");
var text = "";
for (let i = 0; i < athlete_name.length; i++) {
if (athlete_name[i] == person) {
text += "Athlete No - " + (i + 1) + ", Athlete Name is " + athlete_name[i]
+ " and height is " + athlete_height[i] + "<br>";
}
}
document.getElementById("message").innerHTML = text;
if (text == "")
alert(`${person} Invalid Athlete name`);
return "";
}
function Binary_Search(){
}
For my chrome extension, I have a function called storeGroup that returns an object. However, in function storeTabsInfo, when I call storeGroup and set it equal to another object, the parts inside the object are undefined. The object is being populated correctly in storeGroup, so I'm not sure why it's undefined?
function storeTabsInfo(promptUser, group)
{
var tabGroup = {};
chrome.windows.getCurrent(function(currentWindow)
{
chrome.tabs.getAllInWindow(currentWindow.id, function(tabs)
{
/* gets each tab's name and url from an array of tabs and stores them into arrays*/
var tabName = [];
var tabUrl = [];
var tabCount = 0;
for (; tabCount < tabs.length; tabCount++)
{
tabName[tabCount] = tabs[tabCount].title;
tabUrl[tabCount] = tabs[tabCount].url;
}
tabGroup = storeGroup(promptUser, group, tabName, tabUrl, tabCount); // tabGroup does not store object correctly
console.log("tabGroup: " + tabGroup.tabName); // UNDEFINED
chrome.storage.local.set(tabGroup);
})
})
}
function storeGroup(promptUser, group, name, url, count)
{
var groupObject = {};
// current count of group
var groupCountValue = group.groupCount;
var groupName = "groupName" + groupCountValue;
groupObject[groupName] = promptUser;
var tabName = "tabName" + groupCountValue;
groupObject[tabName] = name;
var tabUrl = "tabUrl" + groupCountValue;
groupObject[tabUrl] = url;
var tabCount = "tabCount" + groupCountValue;
groupObject[tabCount] = count;
var groupCount = "groupCount" + groupCountValue;
groupObject[groupCount] = groupCountValue + 1;
// successfully shows parts of groupObject
console.log("Final group: " + groupObject[groupName] + " " + groupObject[tabName] + " " + groupObject[tabUrl] + " " + groupObject[tabCount] + " " + groupObject[groupCount]);
return groupObject;
}
As i said in the comment above you created the groupObject dict keys with the group count so you should use it again to access them or remove it, if you want to use it again although i think this isnt necessary so use:-
... ,tabGroup[tabName + group.groupCount]...
But if you want to get it easily as you wrote just write this code instead of your code:-
function storeGroup(promptUser, group, name, url, count)
{
var groupObject = {};
// current count of group
groupObject['groupName'] = promptUser;
groupObject['tabName'] = name;
groupObject['tabUrl'] = url;
groupObject['tabCount'] = count;
groupObject['groupCount'] = group.groupCount + 1;
// successfully shows parts of groupObject
console.log("Final group: " + groupObject['groupName'] +
" " + groupObject['tabName'] + " " + groupObject['tabUrl'] +
" " + groupObject['tabCount'] + " " +
groupObject['groupCount']);
return groupObject;
}
var swTitle = {};
var favorite = [];
$.each($("input[name='Title']:checked"), function() {
favorite.push($(this).val());
console.log($("input[name='Title']:checked"));
});
swTitle.domain = favorite;
var List = {};
for (var m = 0; m < favorite.length; m++) {
var swTitleObj = [];
$.each($('input[name="' + swTitle.domain[m] + '"]:checked'), function() {
console.log(swTitle.domain[m]);
swTitleObj.push($(this).attr("class"));
console.log(swTitleObj);
});
List[swTitle.domain[m]] = swTitleObj;
}
var swSkillData = " ";
$.each(List, function(key, value) {
console.log(key + ":" + value);
swSkillData += '<li>' + key + ' ' + ':' + ' ' + value + '</li>';
});
Output will be like:
Fruits:Apple,Banana,Orange,Grapes
I want my output be like:
Fruits:Apple,Banana,Orange & Grapes
I have an array of keys and values separated by commas. I want to insert "and" and remove the comma before the last checked element. Kindly help me out with this issue.
I think you can reduce your code, with an option of adding and before the last element like,
var inputs=$("input[name='Title']:checked"),
len=inputs.length,
swSkillData='',
counter=0;// to get the last one
$.each(inputs, function() {
sep=' , '; // add comma as separator
if(counter++==len-1){ // if last element then add and
sep =' and ';
}
swSkillData += '<li>' + this.value + // get value
' ' + ':' + ' ' +
this.className + // get classname
sep + // adding separator here
'</li>';
});
Updated, with and example of changing , to &
$.each(List, function(key, value) {
console.log(key + ":" + value);
var pos = value.lastIndexOf(',');// get last comma index
value = value.substring(0,pos)+' & '+value.substring(pos+1);
swSkillData += '<li>' + key + ' ' + ':' + ' ' + value + '</li>';
});
Snippet
var value ='Apple,Banana,Orange,Grapes';var pos = value.lastIndexOf(',');// get last comma index
value = value.substring(0,pos)+' & '+value.substring(pos+1);
console.log(value);
Here is an easy and customizable form of doing it.
(SOLUTION IS GENERIC)
$(document).ready(function() {
var ara = ['Apple','Banana','Orange','Grapes'];
displayAra(ara);
function displayAra(x) {
var str = '';
for (var i = 0; i < x.length; i++) {
if (i + 1 == x.length) {
str = str.split('');
str.pop();
str = str.join('');
str += ' and ' + x[i];
console.log(str);
$('.displayAra').text(str);
break;
}
str += x[i] + ',';
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Fruits : <span class="displayAra"></span>
str = str.replace(/,(?=[^,]*$)/, 'and')
I solved my own issue. I replaced my last comma with "and" using the above regex. Thanks to Regex!!!
I created minor encrypt method to convert a small string based on distance between characters, but can't for the life of me figure out how to reverse it without knowing the distance between each character from the initial conversion. See image for example how it works imgur.com/Ine4sBo.png
I've already made the encrypt method here (Javascript):
var all = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.#-?").split('');
var position;
//var oKey = "P";
function encrypt() // Encrypt Fixed
{
var sEncode = ("HI-MOM").split('');
var oKey = "P";
for (var i = 0; i < sEncode.length; i++) {
if (all.indexOf(oKey) < all.indexOf(sEncode[i])) {
position = all.indexOf(sEncode[i]) - all.indexOf(oKey);
output.value += "oKey: " + oKey + " distance to sEncode[" + i + "]: " + sEncode[i] + " Count: " + position + " Final Char: " + all[position-1] + "\n";
oKey = sEncode[i];
}
else {
position = all.length - all.indexOf(oKey) + all.indexOf(sEncode[i]);
output.value += "oKey: " + oKey + " distance to sEncode[" + i + "]: " + sEncode[i] + " Count: " + position + " Final Char: " + all[position-1] + "\n";
oKey = sEncode[i];
}
}
}
However, it's the decrypt() method that's killing me.
From what I can tell, your encrypt function can be reduced to this:
var all = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.#-?").split('');
function encrypt(str)
{
var sEncode = str.split('');
var result = '';
var oKey = "P";
for(var i = 0; i < sEncode.length; i++)
{
result += all[(all.indexOf(sEncode[i]) - all.indexOf(oKey) + all.length - 1) % all.length];
oKey = sEncode[i];
}
return result;
}
(I got rid of the if clause by adding all.length either way, and removing it again with the remainder operator if necessary.)
From there, all you need to do is flip the operands (- all.indexOf(oKey) - 1 becomes + all.indexOf(oKey) + 1 (and since we have no more subtractions, adding all.length is no longer necessary)) and reverse the order (so oKey gets assigned the transformed value instead of the original one):
var all = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.#-?").split('');
function decrypt(str)
{
var sEncode = str.split('');
var result = '';
var oKey = "P";
for(var i = 0; i < sEncode.length; i++)
{
oKey = all[(all.indexOf(sEncode[i]) + all.indexOf(oKey) + 1) % all.length];
result += oKey;
}
return result;
}
I'm trying to build a simple site that will check and print out "Buy It Now Prices" for cars. I can't get the JavaScript push function to print out anything but strings.
The eBay API says that buyItNowPrice returns an Amount.
I have experimented with the other Item functions, and the only ones that are working for me are ones that return a String.
The question is, how should the line var itemPrice = item.buyItNowPrice; be formatted to output a number?
function _cb_findItemsByKeywords(root) {
var items = root.findItemsByKeywordsResponse[0].searchResult[0].item || [];
var html = [];
html.push('<table width="100%" border="0" cellspacing="0" cellpadding="3"><tbody>');
for (var i = 0; i < items.length; ++i) {
var item = items[i];
var title = item.title;
var pic = item.galleryURL;
var viewitem = item.viewItemURL;
var itemPrice = item.buyItNowPrice;
var timeLeft = item.watchCount;
if (title != null && null != viewitem) {
html.push('<tr><td>' + '<img src="' + pic + '" border="1">' + '</td>' +
'<td><a href="' + viewitem + '" target="_blank">' +
title + '</a>' // end hyperlink
+
'<br>Item Price: ' + itemPrice +
'<br>Time Remaining: ' + timeLeft +
'</td></tr>');
}
}
html.push('</tbody></table>');
document.getElementById("results").innerHTML = html.join("");
}
// Create a JavaScript array of the item filters you want to use in your request
var filterarray = [{
"name": "MaxPrice",
"value": "250000",
"paramName": "Currency",
"paramValue": "USD"
},
{
"name": "MinPrice",
"value": "15000",
"paramName": "Currency",
"paramValue": "USD"
},
//{"name":"FreeShippingOnly", "value":"false", "paramName":"", "paramValue":""},
{
"name": "ListingType",
"value": ["AuctionWithBIN", "FixedPrice", /*"StoreInventory"*/ ],
"paramName": "",
"paramValue": ""
},
];
// Generates an indexed URL snippet from the array of item filters
var urlfilter = "";
function buildURLArray() {
for (var i = 0; i < filterarray.length; i++) {
var itemfilter = filterarray[i];
for (var index in itemfilter) {
// Check to see if the paramter has a value (some don't)
if (itemfilter[index] !== "") {
if (itemfilter[index] instanceof Array) {
for (var r = 0; r < itemfilter[index].length; r++) {
var value = itemfilter[index][r];
urlfilter += "&itemFilter\(" + i + "\)." + index + "\(" + r + "\)=" + value;
}
} else {
urlfilter += "&itemFilter\(" + i + "\)." + index + "=" + itemfilter[index];
}
}
}
}
}
buildURLArray(filterarray);
// Construct the request
var url = "http://svcs.ebay.com/services/search/FindingService/v1";
url += "?OPERATION-NAME=findItemsByKeywords";
url += "&SERVICE-VERSION=1.0.0";
url += "&SECURITY-APPNAME=REDACTED";
url += "&GLOBAL-ID=EBAY-MOTOR";
url += "&RESPONSE-DATA-FORMAT=JSON";
url += "&callback=_cb_findItemsByKeywords";
url += "&REST-PAYLOAD";
//url += "&categoryId=6001";
url += "&keywords=Ferrari 575";
url += "&paginationInput.entriesPerPage=12";
url += urlfilter;
// Submit the request
s = document.createElement('script'); // create script element
s.src = url;
document.body.appendChild(s);
You are reading the wrong eBay documentation. FindItemsByKeywords is part of the Finding API service. The buyItNowPrice field is found in the item.listingInfo field. Changing the code to the following will output the price.
var itemPrice = '---';
// buyItNowPrice may not be returned for all results.
if(item.listingInfo[0].buyItNowPrice) {
itemPrice = item.listingInfo[0].buyItNowPrice[0]['#currencyId'] + ' ' + item.listingInfo[0].buyItNowPrice[0].__value__;
} else if(item.sellingStatus[0].currentPrice) {
itemPrice = item.sellingStatus[0].currentPrice[0]['#currencyId'] + ' ' + item.sellingStatus[0].currentPrice[0].__value__;
}