Uncaught ReferenceError: variable is not defined on onclick function Javascript - javascript

Today , i have been read all the topic about this but couldn't come up with a solution that's why i am opening this topic.
This is my function which creates the view and i am trying to have a onclick function which should directs to other javascript function where i change the textbox value.
<script type="text/javascript">
$('#submitbtnamazon')
.click(function(evt) {
var x = document.getElementById("term").value;
if (x == null || x == "" || x == "Enter Search Term") {
alert("Please, Enter The Search Term");
return false;
}
listItems = $('#trackList').find('ul').remove();
var searchTerm = $("#term").val();
var url = "clientid=Shazam&field-keywords="
+ searchTerm
+ "&type=TRACK&pagenumber=1&ie=UTF8";
jsRoutes.controllers.AmazonSearchController.amazonSearch(url)
.ajax({
success : function(xml) {
$('#trackList')
.append('<ul data-role="listview"></ul>');
listItems = $('#trackList').find('ul');
html = ''
tracks = xml.getElementsByTagName("track");
for(var i = 0; i < tracks.length; i++) {
var track = tracks[i];
var titles = track.getElementsByTagName("title");
var artists = track.getElementsByTagName("creator");
var albums = track.getElementsByTagName("album");
var images = track.getElementsByTagName("image");
var metaNodes = track.getElementsByTagName("meta");
//trackId ="not found";
trackIds = [];
for (var x = 0; x < metaNodes.length; x++) {
var name = metaNodes[x]
.getAttribute("rel");
if (name == "http://www.amazon.com/dmusic/ASIN") {
trackId = metaNodes[x].textContent;
trackIds.push(trackId);
}
}
for (var j = 0; j < titles.length; j++) {
var trackId=trackIds[j];
html += '<div class="span3">'
html += '<img src="' + images[j].childNodes[0].nodeValue + '"/>';
html += '<h6><a href="#" onclick="someFunction('
+trackId
+ ')">'
+trackId
+ '</a></h6>';
html += '<p><Strong>From Album:</strong>'
+ albums[j].childNodes[0].nodeValue
+ '</p>';
html += '<p><Strong>Artist Name:</strong>'
+ artists[j].childNodes[0].nodeValue
+ '</p>';
html += '<p><Strong>Title:</strong>'
+ titles[j].childNodes[0].nodeValue
+ '</p>';
/*html += '<p><Strong>Created:</strong>'
+ releaseDate
+ '</p>';*/
html += '</div>'
}
}
//listItems.append( html );
$("#track").html(html);
$("#track").dialog({
height : 'auto',
width : 'auto',
title : "Search Results"
});
// Need to refresh list after AJAX call
$('#trackList ul').listview(
"refresh");
}
});
});
</script>
This is my other function where i change the textbox value. it works actually with other values e.g. when i give hardcoded string value. I can see the value in the console but for some reason it gives me the error like :
here the string starts with B is AsinId where i take from amazon. I am definitely in need of help because i am totally stucked.
Uncaught ReferenceError: B00BMQRILU is not defined 62594001:1 onclick
<script type="text/javascript">
function someFunction(var1) {
tracktextbox = document.getElementsByName("trackId");
for (var i = 0; i < tracktextbox.length; i++) {
tracktextbox[i].value = var1;
}
$('#track').dialog('close');
}
</script>

The problem is '<h6><a href="#" onclick="someFunction('+trackId+ ')">', from the error it is clear that trackId is a string value, so you need to enclose it within "" or ''. So try
'<h6><a href="#" onclick="someFunction(\'' + trackId + '\')">'

Related

How to make a leaderboard ranking scores JavaScript

Currently, my code shows the score of the user that's logged in. I want to show the highest score obtained by each user on the leaderboard until the top 10.
js from index.html
<script>
loadRankingTable();
window.onload = () => {
//Check login
if (sessionStorage.loggedInUser !== undefined) {
let oldData = localStorage.getItem(sessionStorage.loggedInUser);
console.log(JSON.parse(oldData))
if (oldData) {
oldData = JSON.parse(oldData);
oldData.topScore = highscore;
localStorage.setItem(sessionStorage.loggedInUser, JSON.stringify(oldData));
}
document.getElementById("Greeting").innerHTML = sessionStorage.loggedInUser;
}
}
</script>
prac.js
function loadRankingTable(){
let str = "<table><tr><th>Rank</th><th>Name</th><th>Score</th></tr>";
for(let key of Object.keys(localStorage)){
let usr = JSON.parse(localStorage[key]);
str += "<tr><td>" + "1" + "</td><td>" + sessionStorage.loggedInUser + "</td><td>" + highscore + "</td></tr>";
}
str += "</table>";
document.getElementById("Ranking").innerHTML = str;
}
The highscore gets stored in the local storage, but I want the logged in user's highscore shown next to their name on the leaderboard, up till the top 10.
Try this: (others have permission to copy and edit this)
function load(){
var userscores = {
"ex1": 10,
"noncy": 40,
"del3tus": 24,
"the_r0ck": 8,
"MONSTER_OSITY": 120
};
var max = 0;
var sorted = [];
for(var prop in userscores){
if(userscores[prop] >= max){
max = userscores[prop];
}
}
var cur = max;
for(var i = max; i > 0; i--){
for(var prop in userscores){
if(userscores[prop] == i){
sorted.push(prop);
}
}
}
var html = "";
for(var i = 0; i < sorted.length; i++){
html = "<tr><td>" + (i + 1) + "</td><td>" + sorted[i] + "</td><td>" + userscores[sorted[i]] + "</td></tr>";
document.getElementById("leaderboard").innerHTML += html;
}
}
<button onclick="load();">Load leaderboard</button>
<table id="leaderboard" border="1" cellSpacing="0px"><tr><th>#</th><th>Name</th><th>Points</th></tr></table>
If that doesn't work, let me know. You can also change it to make it fit better.

how to list all local storage on page properly in javascript?

I am trying to show all my localstorage items value on my index page but for some reason it is not showing. can anyone see what I am doing wrong in my code below. In my index page script I am looping thorough the length of local storage and trying to display them on screen, only thing that display is one item. Please help. thanks for your help.
here is my code (index page script):
document.addEventListener("DOMContentLoaded", function (event) {
var dataFromLocalStorage = "";
for (var i = 0; i < localStorage.length; i++) {
dataFromLocalStorage =
dataFromLocalStorage + " " + localStorage.getItem(`key${i}`);
}
document.querySelector("#content").innerHTML = dataFromLocalStorage; // Updating same thing
})
The other script where I load it to localStorage:
var addToTheContent = document.getElementById("canvas");
var scheduleEvent = document.getElementById("scheduleStartTime");
var candidateId = document.getElementById('candsId');
var getCandId = document.getElementById("candsId");
var displayCandId = candidateId.options[candidateId.selectedIndex].value;
var id = 1;
function addTheEvent() {
var showText = addToTheContent.innerHTML = displayCandId + " ( " + scheduleEvent.value + " ) ";
localStorage.setItem(`key${id}`, JSON.stringify(showText))
id += 1
localStorage.getItem(`key${id}`);
window.location = "/";
}
"key${id}" is a template string, you need to use backticks `` instead of quotation marks "".
You could also loop through localStorage as you normally would for most JavaScript objects:
for(var key in localStorage) {
if(localStorage.hasOwnProperty(key)) { // ignore the prototype methods
// Do whatever you want with key and value found here
console.log(key + ": " + localStorage[key]);
}
}
Typo: Use i instead id
var dataFromLocalStorage = localStorage.getItem(`key${id}`);
correct:
var dataFromLocalStorage = `localStorage.getItem("key${i}");
Another thing, You are updating same innerHTML
var dataFromLocalStorage = "";
for (var i = 0; i < localStorage.length; i++) {
dataFromLocalStorage =
dataFromLocalStorage + " " + localStorage.getItem(`key${i}`);
}
document.querySelector("#content").innerHTML = dataFromLocalStorage; // Updating same thing
// do something with localStorage.getItem(localStorage.key(i));
// missing template string 'key${id}'
var id = 1;
function addTheEvent() {
var showText = displayCandId + " ( " + scheduleEvent.value + " ) ";
localStorage.setItem(`key${id}`, JSON.stringify(showText));
id += 1;
window.location = "/";
}

JS Function Scope with Ebay API

js beginner here. the ebay website has sample code for sending an api request with javascript. the code works out of the box, but the code breaks when i wrap the entire code inside of:
(document).ready( function() {
('button').click( function() {
//(ebays sample code here)
}); });
google chromes console says my error is:
Uncaught ReferenceError: _cb_findItemsByKeywords is not defined
at http://svcs.ebay.com/services/search/FindingService/v1?OPERATION-NAME=findItemsByKeywords&SERVICE-VERSION=1.0.0&SECURITY-APPNAME=micahelr-layitont-PRD-f51ca6568-6366e278&GLOBAL-ID=EBAY-US&RESPONSE-DATA-FORMAT=JSON&callback=_cb_findItemsByKeywords&REST-PAYLOAD&keywords=accord&paginationInput.entriesPerPage=5&itemFilter(0).name=MaxPrice&itemFilter(0).value=30&itemFilter(0).paramName=USD&itemFilter(1).name=ListingType&itemFilter(1).value(0)=AuctionWithBIN&itemFilter(1).value(1)=FixedPrice:1:5
(anonymous) # svcs.ebay.com/services/search/FindingService/v1?OPERATION-NAME=findItemsByKeywords&SERVICE-VERSION=1.0.0&SECURITY-APPNAME=micahelr-layitont-PRD-f51ca6568-6366e278&GLOBAL-ID=EBAY-US&RESPONSE-DATA-FORMAT=JSON&callback=_cb_findItemsByKeywords&REST-PAYLOAD&keywords=accord&paginationInput.entriesPerPage=5&itemFilter(0).name=MaxPrice&itemFilter(0).value=30&itemFilter(0).paramName=USD&itemFilter(1).name=ListingType&itemFilter(1).value(0)=AuctionWithBIN&itemFilter(1).value(1)=FixedPrice:1
what i have come up with, is that the scope of my callback function is incorrect. ive moved the .ready() and .click() statements in many different places within the script tags, trying to solve the problem without completely understanding how it can be fixed. i tried reading about function scope but it seems like its something that i just cant figure out. the following is the content of mt HTML file with embedded JS code:
<html>
<head>
</head>
<body>
<button>click</button>
<script>
$(document).ready(function() {
$('button').click( function() {
var urlfilter = "";
item_MaxPrice = Number(document.getElementById('pagePrice').innerHTML);
inputKeywords = 'accord';
var filterarray = [ {"name":"MaxPrice", "value":item_MaxPrice, "paramName":"USD"}, ];
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">
for (var i = 0; i < items.length; ++i) {
var item = items[i];
html.push('text here');};
document.getElementById("results").innerHTML = html.join("");};
// Generates an indexed URL snippet from the array of item filters
function buildURLArray() {
for(var i=0; i<filterarray.length; i++) {
var itemfilter = filterarray[i];
for(var index in itemfilter) {
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];
}}}}}
// Execute the function to build the URL filter
buildURLArray(filterarray);
var url = "http://svcs.ebay.com/services/search/FindingService/v1";
url += "?OPERATION-NAME=findItemsByKeywords";
url += "&SERVICE-VERSION=1.0.0";
url += "&SECURITY-APPNAME=micahelr-layitont-PRD-f51ca6568-6366e278";
url += "&GLOBAL-ID=EBAY-US";
url += "&RESPONSE-DATA-FORMAT=JSON";
url += "&callback=_cb_findItemsByKeywords";
url += "&REST-PAYLOAD";
url += "&keywords="+inputKeywords;
url += "&paginationInput.entriesPerPage=5";
url += urlfilter;
s=document.createElement('script'); // create script element
s.src= url;
document.body.appendChild(s);
document.write("<a href='" + url + "'>" + url + "</a>");
})});
</script>
</body>
<footer>©darnell cross 2018</footer>
</html>
Uncaught ReferenceError: _cb_findItemsByKeywords is not defined
You are getting this error because Javascript can't find the _cb_findItemsByKeywords function.
What is the problem?
You are creating a script element and adding it to the DOM which is having _cb_findItemsByKeywords function as a callback in the URL.
s=document.createElement('script'); // create script element s.src=
url; document.body.appendChild(s); document.write("" + url + "");
Now, the script would run in the global context and wouldn't find any _cb_findItemsByKeywords function there because you defined it inside of another function.
$(document).ready(function() {...}
(Remember: Every function creates it's own context)
Solution:
Add the _cb_findItemsByKeywords function to the window object.
window._cb_findItemsByKeywords = function() {...}
Hopefully this helps you understand scope with indentation levels. Normally when you indent you use it to help you visualize the levels of scope. A variable declared in a parent scope can be accessed in the child but not the other way around.
<html>
<head>
</head>
<body>
<button>click</button>
<script>
$(document).ready(function() {
$('button').click(function() {
//start of scope
var urlfilter = "";
item_MaxPrice = Number(document.getElementById('pagePrice').innerHTML);
inputKeywords = 'accord';
var filterarray = [{
"name": "MaxPrice",
"value": item_MaxPrice,
"paramName": "USD"
}, ];
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">
for (var i = 0; i < items.length; ++i) {
//start of new scope (can access everything in parent scope but nothing in a scope that is further nested
var item = items[i];
html.push('text here');
//end of new scope
}; document.getElementById("results").innerHTML = html.join("");
};
// Generates an indexed URL snippet from the array of item filters
function buildURLArray() {
for (var i = 0; i < filterarray.length; i++) {
var itemfilter = filterarray[i];
for (var index in itemfilter) {
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];
}
}
}
}
}
// Execute the function to build the URL filter
buildURLArray(filterarray);
var url = "http://svcs.ebay.com/services/search/FindingService/v1";
url += "?OPERATION-NAME=findItemsByKeywords";
url += "&SERVICE-VERSION=1.0.0";
url += "&SECURITY-APPNAME=micahelr-layitont-PRD-f51ca6568-6366e278";
url += "&GLOBAL-ID=EBAY-US";
url += "&RESPONSE-DATA-FORMAT=JSON";
url += "&callback=_cb_findItemsByKeywords";
url += "&REST-PAYLOAD";
url += "&keywords=" + inputKeywords;
url += "&paginationInput.entriesPerPage=5";
url += urlfilter;
s = document.createElement('script'); // create script element
s.src = url;
document.body.appendChild(s);
document.write("<a href='" + url + "'>" + url + "</a>");
})
//end of button scope
});
</script>
</body>
<footer>©darnell cross 2018</footer>
</html>

Only show objects in array that contain a specific string

I was trying to make something where you can type a string, and the js only shows the objects containing this string. For example, I type Address1 and it searches the address value of each one then shows it (here: it would be Name1). Here is my code https://jsfiddle.net/76e40vqg/11/
HTML
<input>
<div id="output"></div>
JS
var data = [{"image":"http://www.w3schools.com/css/img_fjords.jpg","name":"Name1","address":"Address1","rate":"4.4"},
{"image":"http://shushi168.com/data/out/114/38247214-image.png","name":"Name2","address":"Address2","rate":"3.3"},
{"image":"http://www.menucool.com/slider/jsImgSlider/images/image-slider-2.jpg","name":"Name3","address":"Address3","rate":"3.3"}
];
var restoName = [], restoAddress = [], restoRate = [], restoImage= [];
for(i = 0; i < data.length; i++){
restoName.push(data[i].name);
restoAddress.push(data[i].address);
restoRate.push(data[i].rate);
restoImage.push(data[i].image);
}
for(i = 0; i < restoName.length; i++){
document.getElementById('output').innerHTML += "Image : <a href='" + restoImage[i] + "'><div class='thumb' style='background-image:" + 'url("' + restoImage[i] + '");' + "'></div></a><br>" + "Name : " + restoName[i] + "<br>" + "Address : " + restoAddress[i] + "<br>" + "Rate : " + restoRate[i] + "<br>" + i + "<br><hr>";
}
I really tried many things but nothing is working, this is why I am asking here...
Don't store the details as separate arrays. Instead, use a structure similar to the data object returned.
for(i = 0; i < data.length; i++){
if (data[i].address.indexOf(searchedAddress) !== -1) { // Get searchedAddress from user
document.getElementById("output").innerHTML += data[i].name;
}
}
Edits on your JSFiddle: https://jsfiddle.net/76e40vqg/17/
Cheers!
Here is a working solution :
var data = [{"image":"http://www.w3schools.com/css/img_fjords.jpg","name":"Name1","address":"Address1","rate":"4.4"},
{"image":"http://shushi168.com/data/out/114/38247214-image.png","name":"Name2","address":"Address2","rate":"3.3"},
{"image":"http://www.menucool.com/slider/jsImgSlider/images/image-slider-2.jpg","name":"Name3","address":"Address3","rate":"3.3"}
];
document.getElementById('search').onkeyup = search;
var output = document.getElementById('output');
function search(event) {
var value = event.target.value;
output.innerHTML = '';
data.forEach(function(item) {
var found = false;
Object.keys(item).forEach(function(val) {
if(item[val].indexOf(value) > -1) found = true;
});
if(found) {
// ouput your data
var div = document.createElement('div');
div.innerHTML = item.name
output.appendChild(div);
}
});
return true;
}
<input type="search" id="search" />
<div id="output"></div>

Fetching results from LinkedIn API through javascript

First of all thank you for reading this. I am having some trouble fetching the data given by the Linkedin sign-in API with javascript. Here is the script:
<script type="text/javascript">
function onLinkedInAuth() {
IN.API.Profile("me").fields(["firstName","lastName","headline","summary","location","educations","skills"]).result(displayProfiles);
}
function displayProfiles(profiles) {
member = profiles.values[0];
document.getElementById("name").value = member.firstName +" "+ member.lastName;
document.getElementById("pos").value = member.headline;
document.getElementById("city").value = member.location.name;
document.getElementById("sum").value = member.summary;
var i=0;
do {
var oldHTML = document.getElementById('para').innerHTML;
var newHTML = oldHTML + "<tr><td>" + member.educations.values[i].schoolName + "</td></tr>";
document.getElementById('para').innerHTML = newHTML;
i++;
}
while(i<=1);
var v=0;
do {
var oldHTML = document.getElementById('tara').innerHTML;
var newHTML = oldHTML + "<tr><td>" + member.skills.values[v].skill.name + "</td></tr>";
document.getElementById('tara').innerHTML = newHTML;
v++;
}
while(member.skills.values[v].skill.name);
document.getElementById("educ").value = member.educations.values[1].schoolName;
document.getElementById("skills").value = member.skills.values[0].skill.name;
}
</script>
It's a very basic script to get the user infos and, among it, the educational and professional background of the user. The thing is that member.educations.values[i].schoolName and member.skills.values[v].skill.name can have multiple values and I want to gather them all.
It works as long as the specified fields are not empty but then it outputs an error saying that member.skills.values[v] is undefined and it does not run the second loop.
I know the error is really basic but I'm not that great in javascript.
Thanks for your help anyways, have a good day!
You should check the length of the returned values and then loop through them as needed. Something along the lines of:
var educations = member.educations;
if(educations._total > 0) {
for(var i = 0; i < educations._total; i++) {
document.getElementById("educ").value += (i > 0) ? ', ' : '';
document.getElementById("educ").value += educations.values[i].schoolName;
}
}

Categories