How can I limit the display of the content div JSON to three? Now the code shows all the items downloaded from JSON. I would like to only return 3 divs.
<div id="p"></div>
$.getJSON('element.json', function(data){
var a = data.i;
var d = $("<div class='p1'>");
var ele = '';
$.each(a,function(i,v){
ele += "<div class='k'>"+ v.num + "</div>";
});
d.html(ele);
$("#p").append(a);
});
{
"i":[{
"num": "1",
},{
"num": "1",
},{
"num": "3"
},{
"num": "4"
},{
"num": "5",
}]
}
If you only want to retrieve 3 elements from the array you could use slice():
var a = data.i.slice(0, 3);
This could be limited in the if statement to ensure the index doesn't exceed 2.
$.each(a,function(i,v){
if (i>=3){
return false;
}
ele += "<div class='k'>"+ v.num + "</div>";
});
Related
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>";
I am having a list which is nothing but country flag, country name and country code which actually i derived from JSON
and i had written for loop to render the html elements like this
data =
[
{
"name": "INDIA ",
"code": "93",
"url": 'https://www.countryflags.io/in/flat/64.png'
}, {
"name": "JAPAN ",
"code": "355",
"url": 'https://www.countryflags.io/jp/flat/64.png'
}]
for (var i = 0; i < data.length; i++) {
var countryName = data[i].name;
var countrtDialCode = data[i].code;
var countryUrl = data[i].url;
var badge = document.createElement('div');
badge.className = 'badge';
badge.innerHTML =
'<div id="listSection">'+
'<div style="display:flex">'+
'<div id="flagSection">'+'<img style="height:10px;width:20px;margin-top:4px;" src='+countryUrl+'>'+'</div>'+' '+
'<div id="nameSection">' + countryName + '</div>' +' '+
'<div id="codeSection">' + countrtDialCode + '</div>'
+'</div>'+
'</div>'
document.getElementById('countries-list').appendChild(badge);
}
also i have a divs section
<div id="inputSection"> </div>
<div id="countries-list">
</div>
and i have done like when you click on input section the list will come and i can choose from the list and i need ONLY the flag should be shown
<script type="text/javascript">
$(document).ready(function(){
$('#countries-list').addClass('hideSection').removeClass('showSection')
});
$('#inputSection').click(function(){
$('#countries-list').addClass('showSection').removeClass('hideSection')
})
</script>
so when i click india JSON from list , i should display indian flag in inputSection again if i click input section list should come and again if i choose NEPAL, indian flag should be replaced with NEPAL flag.
Have 2 problem.First one i am unable to write click function in INNERHTML to identify which country clicked and second how to retrieve the flag section and show it in inputSection.
Any fiddle will be highly helpful and thankful
If all you need is a clone of the flag section in the input section, then this is all you need:
$('.listSection').on('click', function() {
$('#inputSection').html( $('.flagSection', this).clone() );
});
However, you have to convert every occurrence of id in the HTML in your JS to class, as in the working demo below. Id attribute values should be unique.
$(function() {
const data = [{
"name": "INDIA ",
"code": "93",
"url": 'https://www.countryflags.io/in/flat/64.png'
}, {
"name": "JAPAN ",
"code": "355",
"url": 'https://www.countryflags.io/jp/flat/64.png'
}];
for (var i = 0; i < data.length; i++) {
var countryName = data[i].name;
var countrtDialCode = data[i].code;
var countryUrl = data[i].url;
var badge = document.createElement('div');
badge.className = 'badge';
badge.innerHTML =
'<div class="listSection">'+
'<div style="display:flex">'+
'<div class="flagSection">'+'<img style="height:10px;width:20px;margin-top:4px;" src='+countryUrl+'>'+'</div>'+' '+
'<div class="nameSection">' + countryName + '</div>' +' '+
'<div class="codeSection">' + countrtDialCode + '</div>'
+'</div>'+
'</div>'
document.getElementById('countries-list').appendChild(badge);
}
$('.listSection').on('click', function() {
console.log( {name: $('.nameSection',this).text(), code: $('.codeSection', this).text()} );
$('#inputSection').html( $('.flagSection', this).clone() );
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="inputSection"> </div>
<div id="countries-list">
</div>
NOTE
Since there's not mention in the documentation of .html( jQueryObject ) even thought it works in the above demo, I'll provide an alternative that uses .empty() and .append() methods:
$('#inputSection').empty().append( $('.flagSection', this).clone() );
I've got a menu of coffee, for example, each with it's own parentCategory and I want to render them on the page like so but I'm not entirely sure where to start:
category title
item
item
item
item
category title
item
item
My data model looks like this:
{ "menuItems": [
{
"index": 0,
"parentCategory": "Americanos",
"calories": 234,
"name": "Caffè Americano",
"photos": {
"squareThumb": "http://www.starbucks.com/assets/67c30b9dacd4406db797b1690ac22475.jpg"
}
}, {
"index": 0,
"parentCategory": "Lattes",
"calories": 234,
"name": "Caffè Latte",
"photos": {
"squareThumb": "http://www.starbucks.com/assets/aee68ca3048142f38741f20b30b7a581.jpg"
}
}, {
"index": 0,
"parentCategory": "Mochas",
"calories": 234,
"name": "Caffè Mocha",
"photos": {
"squareThumb": "http://www.starbucks.com/assets/bc15a5ca9d744b66bda07254f2f50013.jpg"
}
}...
and my current script looks like so:
$.getJSON('menu.json', function(drinks) {
var getMenuItem = drinks.menuItems;
var sortedArray = getMenuItem.sort(function(a,b){
return a.parentCategory > b.parentCategory ?1 :-1
})
var output = "";
for (var i in sortedArray) {
output += "<div class='menuItem'><p>" + drinks.menuItems[i].name + "</p><img src='" + drinks.menuItems[i].photos.squareThumb + "'/></div>";
}
document.getElementById("demo").innerHTML=output;
});
Keep the latest category in a variable. Whenever the category changes, start a new <div> for the category.
var last_cat = null;
var output = "";
for (var i in sortedArray) {
var item = sortedArray[i];
if (item.parentCategory != last_cat) {
if (last_cat) { // close the previous category
output += "</div>";
}
output += "<div class='category'><p>" + item.parentCategory + "</p>";
last_cat = item.parentCategory;
}
output += "<div class='menuItem'><p>" + item.name + "</p><img src='" + item.photos.squareThumb + "'/></div>";
}
if (last_cat) {
output += "</div>";
}
This question already has answers here:
Display JSON Data in HTML Table
(9 answers)
Closed 7 years ago.
{
"content": {
"title": "Schema",
"cellValues": [
[
"c1",
"count"
],
[
"DoubleType",
"LongType"
]
],
"id": 3,
"name": "Histogram",
"type": "table"
}
}
I have this JSON coming , from this i want to make a table using javascript or Jquery. The output should be like. The JSON object is coming as cell values in a list , that is creating a problem. I want to map c1 with DoubleType and count with longType in each cell.
c1 count
DoubleType LongType
Please suggest...
Check out this JSFiddle for a running example.
Create Table
function createTable(tableData) {
var tableId = tableData.content.id;
var tableName = tableData.content.name;
var tableTitle = tableData.content.title;
var tableRows = tableData.content.cellValues;
// create table
$('body').append('<table border="1" id="' + tableId + '" name="' + tableName + '"></table>');
// create title
$('#'+tableId).append('<caption>' + tableTitle + '</caption>');
// create rows
for (var i = 0; i < tableRows.length; i++) {
createRow(tableId, tableRows[i]);
}
}
Create Rows and Cells
function createRow(table_id, rowData) {
var row = $("<tr />")
$("#"+table_id).append(row);
// create cells inside this row
for (var i = 0; i < rowData.length; i++) {
row.append($("<td>" + rowData[i] + "</td>"));
}
}
You might be interested in using a plug in such as DataTables which can use a JSON feed as its source.
https://www.datatables.net/
$(function() {
var json = {
"content": {
"title": "Schema",
"cellValues": [
[
"c1",
"count"
],
[
"DoubleType",
"LongType"
]
],
"id": 3,
"name": "Histogram",
"type": "table"
}
};
//Define & initialize vars
var table = $('<table cellspacing="0" cellpadding="3" border="1"/>'),
tbody = $('<tbody/>'),
tr = $('<tr/>'),
td = $('<td/>');
//create rows in tbody
$.each(json.content.cellValues, function(i,v) {
var thisTR = tr.clone();
$.each(v, function(j,u) {
thisTR.append( td.clone().html( u ) );
});
tbody.append( thisTR );
});
//append tbody to table
table.append( tbody );
//append table to DOM
$('#table').html( table );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="table"></div>
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