Using object attribute as image source - javascript

I'm trying to pass the video object's image attribute as the source so I can display the image on the screen when the program runs. For obvious reasons, it can't find the source, because no file has the name 'videoObj1.image'. I was wondering if there is a workaround, maybe to take the text of the attribute and pass that as a source? Or even a way to directly use videoObj1.image. Thanks in advance.
Part of Question2.html where I try to use the image attribute as the source:
function displayVideo(videoObj){
var html = "<h1>Search Result " + "</h1>" + "<b>";
html += "Search keyword: " + videoObj.result.searchKeyword;
html += "<table>";
for(var i=0; i < videoObj.result.video.length; i++){
var videoObj1 = videoObj.result.video[i];
html += "<tr>";
html += "<td>" + "<img src=videoObj1.image>" + "</td>";
html += "<td align='right'>" + videoObj1.channel + "</td>";
html += "<td style='color:green' align='right'>";
html += videoObj1.view;
html += "<img src='stockUp.png' />";
html += "</td>";
html += "<td align='right'>" + videoObj1.link + "%</td>";
html += "</tr>";
}
html += "</table>";
var displayDiv = document.getElementById("display");
displayDiv.innerHTML = html;
}
Question2.json:
{
"result": {
"searchKeyword": "Mathematics",
"video": [
{
"title": "Chaos Game",
"channel": "Numberphile",
"view": "428K",
"link": "http://www.youtube.com/watch?v=kbKtFN71Lfs",
"image": "http://i.ytimg.com/vi/kbKtFN71Lfs/0.jpg",
"length": "8:38"
},
{
"title": "Australian Story: Meet Eddie Woo, the maths teacher you wish you'd
had in high school",
"channel": "ABC News (Australia)",
"view": "223K",
"link": "http://www.youtube.com/watch?v=SjIHB8WzJek",
"image": "http://i.ytimg.com/vi/SjIHB8WzJek/0.jpg",
"length": "28:08"
},
{
"title": "Ham Sandwich Problem",
"channel": "Numberphile",
"view": "557K",
"link": "http://www.youtube.com/watch?v=YCXmUi56rao",
"image": "http://i.ytimg.com/vi/YCXmUi56rao/0.jpg",
"length": "5:53"
},
{
"title": "Magic Square Party Trick",
"channel": "Numberphile",
"view": "312K",
"link": "http://www.youtube.com/watch?v=aQxCnmhqZko",
"image": "http://i.ytimg.com/vi/aQxCnmhqZko/0.jpg",
"length": "3:57"
},
{
"title": "The 8 Queen Problem",
"channel": "Numberphile",
"view": "909K",
"link": "http://www.youtube.com/watch?v=jPcBU0Z2Hj8",
"image": "http://i.ytimg.com/vi/jPcBU0Z2Hj8/0.jpg",
"length": "7:03"
}
]
}
}

The problem is you're passing the string "videoObj1.image" to the img src attribute, which obviously is not going to work.
Rather you should pass the variable either by using classic string concatenation approach like this:
"<td><img src=" + videoObj1.image + "></td>";
OR
Using the recommended and modern template literals approach like this:
`<td><img src=${videoObj1.image}></td>`;

Related

How to display multiple HTML entities in AJAX and JSON?

I need to display this the image below by using an AJAX call tto get tthe JSON file, parse the JSON into a Javascript object, and tthen display the Javascript object on the web page.
At the moment I have been able to display one star for each question in the "Difficulty" column. However, I can't figure outt how to display the correct amount of stars in relation to the JSON code.
Below is my JSON code and below that, the HTML code:
JSON:
{
"studentRefNumber": "BGX8P21R5",
"testResult": [
{
"questionNumber": 1,
"content": "Read a table to solve a problem",
"topic": "Chance & Data",
"correctAnswer": "C",
"yourAnswer": "C",
"difficultyLevel": 1
},
{
"questionNumber": 2,
"content": "Calculate the perimeter of a shape",
"topic": "Measures & Units",
"correctAnswer": "B",
"yourAnswer": "B",
"difficultyLevel": 2
},
{
"questionNumber": 3,
"content": "Solve a word problem involving speed of a vehicle",
"topic": "Algebra & Patterns",
"correctAnswer": "C",
"yourAnswer": "A",
"difficultyLevel": 2
},
{
"questionNumber": 4,
"content": "Solve a word problem involving multiple additions",
"topic": "Algebra & Patterns",
"correctAnswer": "C",
"yourAnswer": "C",
"difficultyLevel": 3
},
{
"questionNumber": 5,
"content": "Identify a shape reflected about a given axis",
"topic": "Space & Geometry",
"correctAnswer": "A",
"yourAnswer": "D",
"difficultyLevel": 5
},
{
"questionNumber": 6,
"content": "Solve a complex problem involving time",
"topic": "Measures & Units",
"correctAnswer": "D",
"yourAnswer": "A",
"difficultyLevel": 3
},
{
"questionNumber": 7,
"content": "Solve a complex problem involving fractions",
"topic": "Number & Arithmetic",
"correctAnswer": "B",
"yourAnswer": "B",
"difficultyLevel": 4
},
{
"questionNumber": 8,
"content": "Solve a complex equation involving two variables",
"topic": "Number & Arithmetic",
"correctAnswer": "C",
"yourAnswer": "B",
"difficultyLevel": 5
},
{
"questionNumber": 9,
"content": "Identify an object shown from a different position",
"topic": "Space & Geometry",
"correctAnswer": "B",
"yourAnswer": "B",
"difficultyLevel": 4
},
{
"questionNumber": 10,
"content": "Translate data table into a graph",
"topic": "Chance & Data",
"correctAnswer": "A",
"yourAnswer": "A",
"difficultyLevel": 1
}
]
}
HTML:
<html>
<head>
<script>
function makeAjaxQueryTestResult(){
//create XMLHttpRequest
var xhttp = new XMLHttpRequest();
//create a handler for the readyState change
xhttp.onreadystatechange = function() {
readyStateChangeHandler(xhttp);
};
//get JSON file by making async call
xhttp.open("GET", "Question4.json", true);
xhttp.send();
}
function readyStateChangeHandler(xhttp){
if (xhttp.readyState == 4){
// readyState = 4 means DONE
if(xhttp.status == 200){
// status = 200 means OK
handleStatusSuccess(xhttp);
}else{
// status is NOT OK
handleStatusFailure(xhttp);
}
}
}
// XMLHttpRequest failed
function handleStatusFailure(xhttp){
// display error message
var displayDiv = document.getElementById("display");
displayDiv.innerHTML = "XMLHttpRequest failed: status " + xhttp.status;
}
// XMLHttpRequest success
function handleStatusSuccess(xhttp){
var jsonText = xhttp.responseText;
// parse the json into an object
var testResultObj = JSON.parse(jsonText);
// display the object on the page
displayTestResult(testResultObj);
}
// display the object on the page
function displayTestResult(testResultObj){
// print the testResultObj on the console
// console.log(testResultObj);
// construct HTML code to display information
var html = "<h2>Test Result. Student Reference Number: " + testResultObj.studentRefNumber + "</h2>";
html += "You scored 6 out of 10";
html += "<br /><br />";
html += "<table border='1'>";
html += "<tr><th>Question</th><th>Content</th><th>Topic</th><th>Correct Answer</th><th>Your Answer</th><th>Difficulty</th></tr>";
for(var i=0; i < testResultObj.testResult.length; i++){
var testObj = testResultObj.testResult[i];
html += "<tr>";
html += "<td>" + testObj.questionNumber + "</td>";
html += "<td>" + testObj.content + "</td>";
html += "<td>" + testObj.topic + "</td>";
html += "<td>" + testObj.correctAnswer + "</td>";
if (testObj.yourAnswer == testObj.correctAnswer){
html += "<td align='center' style='color:green'>";
html += "✓";
html += "</td>";
}else{
html += "<td align='center'>" + testObj.yourAnswer + "</td>";
}
var starLvl = "⭐" * testObj.difficultyLevel;
html += "<td>" + starLvl + "</td>";
}
var displayDiv = document.getElementById("display");
displayDiv.innerHTML = html;
}
</script>
</head>
<body>
<button onClick="makeAjaxQueryTestResult()">Get Test Result</button>
<br /> <br />
<div id="display">
</div>
</body>
</html>
You need to loop N times, corresponding to your difficulty level.
var starLvl = "";
for(let i=0; i < testObj.difficultyLevel; i++) {
starLvl += "⭐"; // concatenates N stars
}
html += "<td>" + starLvl + "</td>";

How to add table headers to dynamically generated table containing Ajax data?

I am attempting to dynamically add the table header from the JSON data.
I need to generate the header (th) as well so that it is not done manually.
I have a very basic working example: And I am familiar with the JQuery solution, however, I would like to do this in a JavaScript only approach:
Some JSON formatted data:
var value = [{
"City": "KABUL",
"Continent": "ASIA",
"Country": "AFGHANISTAN",
"CountryAbbr": "AF",
"CountryId": "102120"
}, {
"City": "MARIEHAMN",
"Continent": "EUROPE",
"Country": "ALAND ISLANDS",
"CountryAbbr": "AX",
"CountryId": "102115"
}];
JavaScript:
var out = "<table>";
for ( var i = 0; i < value.length; i++) {
out += "<tr><td>" + value[i].Country +
"</td><td>" + value[i].City +
"</td><td>" + value[i].CountryAbbr +
"</td></tr>";
}
out += "</table>";
document.getElementById("tableContainer").innerHTML = out;
HTML:
<div id="tableContainer"></div>
A working fiddle:
dynamically generated table containing Ajax data
If you are talking about table header/heading.then the below code is helpful to you:
var value = [{
"City": "KABUL",
"Continent": "ASIA",
"Country": "AFGHANISTAN",
"CountryAbbr": "AF",
"CountryId": "102120"
}, {
"City": "MARIEHAMN",
"Continent": "EUROPE",
"Country": "ALAND ISLANDS",
"CountryAbbr": "AX",
"CountryId": "102115"
}];
var out = "<table>";
out+="<tr><th>Country</th><th>City</th><th>Country Code</th></tr>";//TABLE HEADER/HEADING----------
for ( var i = 0; i < value.length; i++ ) {
out += "<tr><td>" + value[i].Country +
"</td><td>" + value[i].City +
"</td><td>" + value[i].CountryAbbr +
"</td></tr>";
}
out += "</table>";
document.getElementById("tableContainer").innerHTML = out;

display images from json object array

i'm trying to output a series of images in html from an external json file. Unfortunately i cannot change the way the json is formatted and i can't seem to find the right way to access the image urls to use them as src attribute.
this is the code i came up with
$.getJSON( "json/data.json", function( data ) {
var mhtml = '';
$.each(data["item"].images, function(key, val){
for (var i=0; i< data["item"].images.length; i++) {
var img = data["item"]images[i];
}
var alt = data["item"].name;
mhtml += '<li><div class=""><img src="'+val.img+'" /></div>';
mhtml += '<h1 class="title">'+alt+'</h1>';
mhtml += '</li>';
});
var $ul = $('<ul>').append($(mhtml));.
$('#mydiv').append($ul);
});
it successfully counts the images and outputs elements but i can't access the url parameters.
this is how the json file is formatted
{
"item": {
"name": "blue dress",
"details": "graphic print, Logo.",
"composition": "Composition: 94% Cotton, 6% Elastam.",
"modelDetails": [
"Modeal wearing a size M",
"Measures: 86 - 60 - 90",
"Height: 178cm"
],
"images": [
"http://cdn.myoutfits.biz/41/xxxxxxx_001.jpg",
"http://cdn.myoutfits.biz/41/xxxxxxx_002.jpg",
"http://cdn.myoutfits.biz/41/xxxxxxx_003.jpg",
"http://cdn.myoutfits.biz/41/xxxxxxx_004.jpg"
]
}
}
thanks everyone for helping
You have several issues.
looping over the images twice - $.each is a loop
getting the alt each time.
val.img does not exist
Here is a working version - do make sure it is run after mydiv exists
data = {
"item": {
"name": "blue dress",
"details": "graphic print, Logo.",
"composition": "Composition: 94% Cotton, 6% Elastam.",
"modelDetails": [
"Modeal wearing a size M",
"Measures: 86 - 60 - 90",
"Height: 178cm"],
"images": [
"http://cdn.myoutfits.biz/41/xxxxxxx_001.jpg",
"http://cdn.myoutfits.biz/41/xxxxxxx_002.jpg",
"http://cdn.myoutfits.biz/41/xxxxxxx_003.jpg",
"http://cdn.myoutfits.biz/41/xxxxxxx_004.jpg"]
}
}
var alt = data["item"].name,mhtml="";
$.each(data["item"].images, function (i, img) {
mhtml += '<li><div class=""><img src="' + img + '" /></div>';
mhtml += '<h1 class="title">' + alt + '</h1>';
mhtml += '</li>';
});
var $ul = $('<ul>').append($(mhtml));
$('#mydiv').append($ul);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="mydiv"></div>
Check if this can help you
var data = {
"item": {
"name": "blue dress",
"details": "graphic print, Logo.",
"composition": "Composition: 94% Cotton, 6% Elastam.",
"modelDetails": [
"Modeal wearing a size M",
"Measures: 86 - 60 - 90",
"Height: 178cm"
],
"images": [
"http://cdn.myoutfits.biz/41/xxxxxxx_001.jpg",
"http://cdn.myoutfits.biz/41/xxxxxxx_002.jpg",
"http://cdn.myoutfits.biz/41/xxxxxxx_003.jpg",
"http://cdn.myoutfits.biz/41/xxxxxxx_004.jpg"
]
}
}
$(document).ready(function(){
console.log(data.item.images);
var alt = data.item.name;
var mhtml="";
$.each(data.item.images,function(k,v){
mhtml += '<li><div class=""><img src="'+data.item.images[k]+'" /></div>';
mhtml += '<h1 class="title">'+alt+'</h1>';
mhtml += '</li>';
})
alert(mhtml)
console.log(mhtml)
$('#mydiv').append(mhtml);
});
http://plnkr.co/edit/kz2WI6FEk0atgoUFJ0Jf?p=preview
you do a foreach and a for ... i don't understand why you do the internal cicle (the for).
If you change
mhtml += '<li><div class=""><img src="'+val.img+'" /></div>';
into
mhtml += '<li><div class=""><img src="'+val+'" /></div>';
you can see some image

on change of div based drop down jquery

I have a drop down based on a JSON Object and the purpose of this to render a drop down box.
var Regions =
{
"ErrorInfo": {
"Success": true,
"ErrorCode": "",
"Program": "",
"Method": "",
"Message": "",
"Details": "",
"StackTrace": "",
"ErrorList": null
},
"Results": {
"DimName": "region",
"SubsetName": "",
"Members": [{
"ID": "CEurope",
"Name": "Central Europe",
"Children": [],
"Hierarchy": [],
"Attributes": []
},
{
"ID": "SEurope",
"Name": "Southern Europe",
"Children": null,
"Hierarchy": [],
"Attributes": []
}]
}
};
//var htmlStr = '';
var icount=0;
var mySelect = $('#options');
var optionsValues = '<select>';
$.each(Regions, function(){
optionsValues += '<option value="' + Regions.Results.Members[icount].ID + '">' + Regions.Results.Members[icount].Name + '</option>';
icount=icount+1;
});
optionsValues += '</select>';
var options = $('#options');
options.replaceWith(optionsValues);
This is my Javascript which is working but happy to refine the code so that I can learn the finer points of JS.
My HTML is like this
<!DOCTYPE html>
<html>
<head>
<title>JavaScript & jQuery - Chapter 13: Form Enhancement and Validation - Populate a selectbox</title>
<link rel="stylesheet" href="css/c13.css" />
</head>
<body>
<form name="howHeard" id="howHeard" action="/heard" method="post">
<div id="page">
</div>
<div id="options">
</div>
<script src="js/jquery-1.9.1.js"></script>
<script src="js/124.js"></script>
</body>
</html>
My question is how do I detect an on change event of my drop down list.
Any help would be appreciated as I learn through the maze of jquery javascript etc.
Cheerio
This should do it:
options.change(function() {
alert( "It changed!" );
});
ref: https://api.jquery.com/change/
Some refinement in your JS:
//var icount=0; ->Not needed
//var mySelect = $('#options'); ->Not needed
var optionsValues = '<select id="mySelect">';
$.each(Regions, function(index){
optionsValues += '<option value="' + Regions.Results.Members[index].ID + '">' + Regions.Results.Members[index].Name + '</option>';
//icount=icount+1;-> Not needed
});
optionsValues += '</select>';
var options = $('#options');
options.replaceWith(optionsValues);
Basically for the above set-up, below code should work:
$("#mySelect").on('change',function(){
//do stuff here
});
Or if its dynamic element the below should definitely work:
$(document).on('change',"#mySelect",function(){
//do stuff here
});
UPDATE
WORKING DEMO TO CLARIFY YOUR DOUBTS
Bit more refinement on your JS:
var members=Regions.Results.Members; //Get all the members in a single variable
var optionsValues = '<select id="mySelect">';
//loop here for only member variables
$.each(members, function(index,value){
optionsValues += '<option value="' + value.ID + '">' + value.Name + '</option>';
});
optionsValues += '</select>';
var options = $('#options');
options.replaceWith(optionsValues);

innerHTML is not getting updated

I am trying to get the data from the string and i want to display it in my html.
Here is the code what i tried
var jsn = {
"channels": [{
"name": "video1",
"image": "images/bodyguard.jpg"
}, {
"name": "video2",
"image": "images/bodyguard.jpg"
}, {
"name": "video3",
"image": "images/bodyguard.jpg"
}, {
"name": "video4",
"image": "images/bodyguard.jpg"
}, {
"name": "video5",
"image": "images/bodyguard.jpg"
}]
};
var id = document.getElementById("menu_list");
var inHtm = "";
var channels = jsn.channels.length;
var cha = jsn.channels;
alert("channels : " + channels);
if (channels != undefined) {
for (var i = 0, len = channels; i < len; ++i) {
var item = cha[i].name;
alert(item);
//var name = item.name;
var image = cha[i].image;
inHtm += '<div class="menu"><a href="javascript:void(0);" onkeydown="Main.keyDown();" >';
inHtm += '<img src="' + image + '"/>';
inHtm += '</a></div>';
}
alert(inHtm);
in1.innerHtml = inHtm;
}
My Fiddle
It is assigning the values to inHtm but my innerHTML is not getting updated. I want to display the image in my html
This:
in1.innerHtml = inHtm;
Should be:
id.innerHTML = inHtm;
Your object is id not in1 and the property is innerHTML not innerHtml.
Also I suggest using console.log() for degbugging instead of alert(). alerts are painful especially in loops, and with console.log() you can dump entire objects, whereas alert will just show "object".
Corrected fiddle

Categories

Resources