How to display information relative to image clicked using pokemon API? - javascript

I'm trying to get and display the image and information of a clicked pokemon from pokemon API
HTML code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script src="pokedex2.js"></script>
<link rel="stylesheet" href="pokedex2.css">
<title>Pokedex v 2.0</title>
</head>
<body>
<div id="all">
<div id="pokemon">
</div>
<div id="chosen">
</div>
</div>
</body>
</html>
JavaScript
$(document).ready(function(){
for(i = 1; i <=151; i ++){
$("#pokemon").append("<img id=pokepic" + i + "
src='http://pokeapi.co/media/img/" + i +
".png'>");
}
var clicked = false;
$("img").click(function(){
clicked = true;
console.log(this);
if(clicked){
$.get("http://pokeapi.co/api/v1/pokemon/" + i +"/", function(data){
var str = "";
str += "<h4>Types</h4>";
str += "<ul>";
var str2 = "";
str2 += "<h4>height</h4>";
str2 += "<ul>";
var str3 = "";
str3 += "<h4>weight</h4>";
str3 += "<ul>";
for(i = 0; i < data.types.length; i ++){
str += "<li>" + data.types[i].name + "</li>";
}
str2 += "<li>" + data.height + "</li>";
str3 += "<li>" + data.weight + "</li>";
str += "</ul>"
str2 += "</ul>"
str3 += "</ul>"
$("#chosen").html(str + str2 + str3); }, "json");
}
else{
clicked = false;
}
})
});
At the moment, the only information being brought up are for the first 3 pokemon in the list, not for the pokemon that was clicked. I need to find the information associated with the clicked pokemon, like a pokedex.
I included console.log to show that whichever image is clicked, the picture, and pokepic ID number associated with that image appear in the console. Instead what I need is for the image and stats associated with each image to appear in the div labeled chosen

Your click event uses the i variable defined in your for loop. Since the function inside the click is always called after the loop is done, i is always 152. You need to read the current pokemon from your click event:
$('img').on('click', function(e){
var pokemonId = e.target.id.split('pokepic')[1];
$.get("http://pokeapi.co/api/v1/pokemon/" + pokemonId +"/", function(data){
...
});
});

Related

I want to prevent user from entering a duplicate value in array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
full:
https://onlinegdb.com/HJN6CGLTD
I need help in here : want a code that check input1 and see if its already in array or not if it is error if not push it in array.
function AddPoints()
{
var item = document.getElementById("input1").value;
if (points.includes(item) === false) points.push(parseInt( item )); // duplicate check
else document.getElementById("demo2").innerHTML = "The number Exist" ; // duplicate error
displayPoints();
}
if i understand your question you can try this code:
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<label>input</label>
<input id="input1" type="text"/>
<input type="button" value="Add" onclick="AddPoints()"/>
<div id="demo"></div>
<div id="demo2"></div>
</body>
</html>
JS:
var i;
var points=[];
function AddPoints(){
var item = document.getElementById("input1").value;
item=parseInt(item);//only integer number
// I check if the item is a integer number
if(Number.isInteger(item)){
//when the item's value is not present in the array
if (points.includes(item,0) === false) {
points.push( item ); // new value
document.getElementById("demo2").innerHTML = "" ;
//displayPoints();
}
else {
document.getElementById("demo2").innerHTML = "The number Exist" ; // duplicate error
//displayPoints();
}
}
else{
document.getElementById("demo2").innerHTML = "The number error" ; // It is not a number
}
displayPoints();
}
function displayPoints(){
var i;
text = "<table border=1>";
for (i = 0; i < points.length; i++) {
text += "<tr>";
text += "<td>" + (i+1) + "</td>";
text += "<td>" + points[i] + "</td>";
text += "</tr>"
}
text += "<table>";
document.getElementById("demo").innerHTML = text;
}
this is a test with the code
var i;
var points=[];
function AddPoints(){
var item = document.getElementById("input1").value;
item=parseInt(item);//only integer number
if(Number.isInteger(item)){
if (points.includes(item,0) === false) {
points.push( item );// new value
document.getElementById("demo2").innerHTML = "" ;
//displayPoints();
}
else {
document.getElementById("demo2").innerHTML = "The number Exist" ; // duplicate error
//displayPoints();
}
}
else{
document.getElementById("demo2").innerHTML = "The number error" ; // It is not a number
}
displayPoints();
}
function displayPoints(){
var i;
text = "<table border=1>";
for (i = 0; i < points.length; i++) {
text += "<tr>";
text += "<td>" + (i+1) + "</td>";
text += "<td>" + points[i] + "</td>";
text += "</tr>"
}
text += "<table>";
document.getElementById("demo").innerHTML = text;
}
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<script>
</script>
<body>
<label>input</label>
<input id="input1" type="text"/>
<input type="button" value="Add" onclick="AddPoints()"/>
<div id="demo"></div>
<div id="demo2"></div>
</body>
</html>

TypeError when parsing Blogger API response: Cannot read property 'url' of undefined

I'm parsing JSON feed from the blogger API but its throwing following error:
37:59 Uncaught TypeError: Cannot read property 'url' of undefined
Previously it was working fine, there weren't any issues but suddenly the error keeps coming up and nothing is displaying. I have looked for stackoverflow and followed this post as well but the error is not going away. Maybe blogger has changed their object nodes that i can't figure out.
Javascript Code:
<script type="text/javascript">
function mycallback(json) {
for (var i = 0; i < json.feed.entry.length; i++) {
for (var j = 0; j < json.feed.entry[i].link.length; j++) {
if (json.feed.entry[i].link[j].rel == 'alternate') {
var postUrl = json.feed.entry[i].link[j].href;
break;
}
}
var postTitle = json.feed.entry[i].title.$t;
var postAuthor = json.feed.entry[i].author[0].name.$t;
var postSummary = json.feed.entry[i].summary.$t;
var entryShort = postSummary.substring(0,400);
var entryEnd = entryShort.lastIndexOf(" ");
var postContent = entryShort.substring(0, entryEnd) + '...';
var postImage = json.feed.entry[i].media$thumbnail.url.replace('s72-c/','s640/');
var postTimestamp = json.feed.entry[i].published.$t;
var item = '<div class="col-md-3 mb-4 blogpost-main">';
var item = item + '<div class="card h-100">';
var item = item + '<img class="card-img-top" src="' + postImage + '"/>';
var item = item + '<div class="card-body">';
var item = item + '' + postTitle + '</h6>';
var item = item + '<p class="card-text text-muted"><i class="far fa-clock" style="color: #888"></i> <time class="timeago" datetime= '+ postTimestamp +'>' + postTimestamp + '</time></p>';
var item = item + '</div>';
var item = item + '</div>';
var item = item + '</div>';
//document.write(item);
document.getElementById("news").appendChild(item);
console.log(item);
}
}
</script>
<script src="https://www.wallpapersoverflow.com/feeds/posts/summary?orderby=published&max-results=4&alt=json-in-script&callback=mycallback"></script>
<div id="news"></div>
JsFiddle: https://jsfiddle.net/645pg9rz/
If you run console.log(json.feed.entry) in your fiddle, you'll see that there is no key called media$thumbnail in the returned objects. That is why your code is failing at var postImage = json.feed.entry[i].media$thumbnail.url.replace('s72-c/','s640/'); - it is trying to access the url property of an item that doesn't exist.
Perhaps the API used to use that key and no longer does, or there are just no thumbnails available in the entries you requested. I don't see a new key with an image file other than the Blogger logo.
Updated: the pictures you're trying to reach are not in the object that came to you. that's why you get the error. (json.feed.entry[i].media$thumbnail)
there are no pictures in the object that came to you. It's the only icon that comes. I put them.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<title>Document</title>
<style>
</style>
</head>
<body>
<div class="row" id="news"></div>
<script>
function mycallback(json) {
console.log(json)
for (var i = 0; i < json.feed.entry.length; i++) {
for (var j = 0; j < json.feed.entry[i].link.length; j++) {
if (json.feed.entry[i].link[j].rel == 'alternate') {
var postUrl = json.feed.entry[i].link[j].href;
break;
}
}
var postTitle = json.feed.entry[i].title.$t;
var postAuthor = json.feed.entry[i].author[0].name.$t;
var postSummary = json.feed.entry[i].summary.$t;
var entryShort = postSummary.substring(0, 400);
var entryEnd = entryShort.lastIndexOf(" ");
var postContent = entryShort.substring(0, entryEnd) + '...';
var postImage = json.feed.entry[i].author[0].gd$image.src;
var postTimestamp = json.feed.entry[i].published.$t;
console.log(postImage)
var item = '<div class="col-md-3 mb-4 blogpost-main">';
var item = item + '<div class="card h-100">';
var item = item + '<img class="card-img-top" src="' + postImage + '"/>';
var item = item + '<div class="card-body">';
var item = item + '' + postTitle + '</h6>';
var item = item + '<p class="card-text text-muted"><i class="far fa-clock" style="color: #888"></i> <time class="timeago" datetime= ' + postTimestamp + '>' + postTimestamp + '</time></p>';
var item = item + '</div>';
var item = item + '</div>';
var item = item + '</div>';
document.getElementById("news").innerHTML += item;
}
}
</script>
<script src="https://www.wallpapersoverflow.com/feeds/posts/summary?orderby=published&max-results=4&alt=json-in-script&callback=mycallback"></script>
</body>
</html>

How To Convert CSV file to HTML table

i have csv file with the content :
heading1,heading2,heading3,heading4,heading5
value1_1,value2_1,value3_1,value4_1,value5_1
value1_2,value2_2,value3_2,value4_2,value5_2
I create Javascript/HTML code to pick up that file and display the content
<html>
<head>
<title>show csv</title>
</head>
<body>
<input type="file" id="fileinput" multiple />
<div id="result"></div>
<script type="text/javascript">
function readMultipleFiles(evt) {
//Retrieve all the files from the FileList object
var files = evt.target.files;
if (files) {
for (var i=0, f; f=files[i]; i++) {
var r = new FileReader();
r.onload = (function(f) {
return function(e) {
var contents = e.target.result;
var res = document.getElementById("result");
res.innerHTML = "Got the file<br>"
+"name: " + f.name + "<br>"
+"type: " + f.type + "<br>"
+"size: " + f.size + " bytes</br>"
+ "starts with: " + contents;
};
})(f);
r.readAsText(f);
}
} else {
alert("Failed to load files");
}
}
document.getElementById('fileinput').addEventListener('change',readMultipleFiles, false);
</script>
</body>
</html>
and the output is like :
output
question : How can i convert the content or the data to array and showing as html table ?
thanks for any help.
You can convert csv data into array and then into html table. I have added \n into your new line. Please add the \n to your code when there is a new line.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
table {
border-collapse: collapse;
border: 2px black solid;
font: 12px sans-serif;
}
td {
border: 1px black solid;
padding: 5px;
}
</style>
</head>
<body>
<div id='container'></div>
<script type="text/javascript"charset="utf-8">
var data = 'heading1,heading2,heading3,heading4,heading5\nvalue1_1,value2_1,value3_1,value4_1,value5_1\nvalue1_2,value2_2,value3_2,value4_2,value5_2';
var lines = data.split("\n"),
output = [],
i;
for (i = 0; i < lines.length; i++)
output.push("<tr><td>"
+ lines[i].slice(0,-1).split(",").join("</td><td>")
+ "</td></tr>");
output = "<table>" + output.join("") + "</table>";
var div = document.getElementById('container');
div.innerHTML = output;
</script>
</body>
</html>
I found Kapila Perera's answer to be very useful. However, the last element of each row was being cropped due to the slice(0,-1) use. Building on Perera's answer, in the example below I've used slice() instead.
I've also separated out the first row lines[0] as a header row and loop from 1 instead (which won't always be the case that csv contains headers but is explicitly called out in the example).
Finally, I've added the tbody tags when the output gets wrapped but this probably isn't required.
<script type="text/javascript"charset="utf-8">
var div = document.getElementById('container');
var data = 'heading1,heading2,heading3,heading4,heading5\nvalue1_1,value2_1,value3_1,value4_1,value5_1\nvalue1_2,value2_2,value3_2,value4_2,value5_2';
var lines = data.split("\n"), output = [], i;
/* HEADERS */
output.push("<tr><th>"
+ lines[0].slice().split(",").join("</th><th>")
+ "</th></tr>");
for (i = 1; i < lines.length; i++)
output.push("<tr><td>"
+ lines[i].slice().split(",").join("</td><td>")
+ "</td></tr>");
output = "<table><tbody>"
+ output.join("") + "</tbody></table>";
div.innerHTML = output;
</script>

Geo Location Trace getElementById not working

I am working on a challenge by freecodecamp, Task is to show the local weather and hence I have to get the location of the user. I can get the location from here but after printing that i was trying to getElementById of a div i have printed using JS which gives null in response. I want to get the key value pair so that i can do stuff with them. Here is my code:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>Location Trace | freecodecamp Challanges</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<div id="GeoResults"></div>
<script>
$.getJSON("http://ip-api.com/json/?callback=?", function(data) {
var table_body = "";
var count = 0;
$.each(data, function(k, v) {
//JSON.stringify(j); // '{"name":"binchen"}'
table_body += '<div id=Coun_'+count+'>'+v+'</div>';
//table_body += "<tr><td id='FC_"+count+"'>" + k + "</td><td><b id='SC_"+count+"'>" + v + "</b></td></tr>";
count++;
});
$("#GeoResults").html(table_body);
});
</script>
<script>
var x = document.getElementById('Coun_1') /*= 'Dooone!!!'*/;
console.log(x);
</script>
</body>
</html>
Thanks in Advance!
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>Location Trace | freecodecamp Challanges</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<div id="GeoResults"></div>
<script>
$.getJSON("http://ip-api.com/json/?callback=?", function(data) {
var table_body = "";
var count = 0;
$.each(data, function(k, v) {
//JSON.stringify(j); // '{"name":"binchen"}'
table_body += '<div id=Coun_'+count+'>'+v+'</div>';
//table_body += "<tr><td id='FC_"+count+"'>" + k + "</td><td><b id='SC_"+count+"'>" + v + "</b></td></tr>";
count++;
});
$("#GeoResults").html(table_body);
var x = document.getElementById('Coun_1').innerHTML; /*= 'Dooone!!!'*/;
console.log(x);
});
</script>
</body>
</html>

Create HTML table with hyperlink from JSON Object

I have an application which returns a JSONObject. I am able to get data from JSON object using below code.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<head>
<style type="text/css">
table, td, th
{
border:1px collapse black;
font-family:Arial;
font-size :small;
}
th
{
background-color:green;
color:white;
}
.hideMe
{
/*display : none;*/
/*visibility: hidden;*/
}
</style>
<script type="text/javascript" language="jscript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js">
</script>
<script type="text/javascript" language="javascript">
var host = "somehost";
var mystr = "http://"+ host +"/rest/bpm/wle/v1/exposed/process"; // use get for this
var ulink = "";
$(document).ready(function () {
$.get(mystr, function (data) {
var obj = JSON.parse(data);
var thtml = "<table id='proctable'>";
for (i = 0; i < obj.data.exposedItemsList.length; i++) {
ulink = "http://" + host + obj.data.exposedItemsList[i].startURL;
thtml = thtml + "<tr><td><a onclick='my_function()' href='javascript:void(0)'>" + obj.data.exposedItemsList[i].display + "</a></td><td id='linkcell' class='hideMe'>" + ulink + "</td></tr>";
}
thtml = thtml + "</table>";
document.getElementById('contentdiv').innerHTML = thtml;
});
});
//javascript
my_function = null;
//jquery
$(function () {
function generateBPDInstance() {
$.post(ulink, function (taskdata) {
var tobj = JSON.parse(taskdata);
alert(tobj.data.tasks[0].name);
alert(tobj.data.tasks[0].tkiid);
});
}
my_function = generateBPDInstance;
ulink = "";
})
`
</script>
</head>
<body>
<form name="myform">
<div id="contentdiv">
<table id="proctable">
</table>
</div>
</form>
</body>
</html>
The above html creates a table showing a list of the returned values. I also want to get rowIndex of hyperlink and pass value of column2 to function generateBPDInstance.
I am not so good at HTML and Jquery. Please suggest how can I get rowIndex for HTML table which is created through javascript.
Thanks in advance.
The simple way is :
change your table building to this
for (i = 0; i < obj.data.exposedItemsList.length; i++) {
ulink = "http://" + host + obj.data.exposedItemsList[i].startURL;
thtml = thtml + "" + obj.data.exposedItemsList[i].display + "" + ulink + "";
function my_function(e){
//e is the row index and when you call document.getLementById("proctable").rows[e]; this will give you the complete row.
}
--this is a simple way, and if you want traverse the tree and get , you always have parentnode or you can use jquery $(object).parent() to get the parent of hyperlink and traverse.
You problem is "pass value of column2 to function generateBPDInstance". Why not pass it already while generating the table?
for (i = 0; i < obj.data.exposedItemsList.length; i++) {
ulink = "http://" + host + obj.data.exposedItemsList[i].startURL;
thtml = thtml + "<tr><td><a onclick='my_function('" + ulink + "')' href='javascript:void(0)'>" + obj.data.exposedItemsList[i].display + "</a></td><td id='linkcell' class='hideMe'>" + ulink + "</td></tr>";
// ------------------------------------------------------^ pass the value
}
Add parameter to your function generateBPDInstance
function generateBPDInstance(ulink) {
//--------------------------^----
$.post(ulink, function (taskdata) {
var tobj = JSON.parse(taskdata);
alert(tobj.data.tasks[0].name);
alert(tobj.data.tasks[0].tkiid);
});
}

Categories