for json Element id = "1" , append ul 'chapter_count' times - javascript

I am fairly new to web dev and This is my first question on StackOverflow. Apologies if I didn't frame it properly.
Here is my json.
{
"books":
[
{
"_id": "1",
"book_cat": "OLD",
"book_eng_name": "Book1",
"chapter_count": "50"
},
{
"_id": "2",
"book_cat": "OLD",
"book_eng_name": "Book2",
"chapter_count": "40""
}
]
I want to use this json with jquery to append to . First I need to filter __id and then append a statement to the <ul> "Chapter_count" times.
For instance, if I select I am searching for _id 1 I want 50 item list that says
Chapter 1
Chapter 2
...
...
...
Chapter 50
I want to append to ul in the following html:
<html>
<title>Chapters</title>
<body>
<ul></ul>
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/
jquery.min.js"></script>
<script type = "text/javascript" src='files/js/Chapter_script.js'></script>
<script type = "text/javascript" src='files/js/books.json'></script>
</body>
</html>
I wrote something like this but didn't work :(
(document).ready(function(){
var search_id = window.location.search;
var chapter_no = search_id.match(/\d+/g);
$.getJSON("files/js/books.json",function(data){
$.each(data.books, function(){
if (this['_id'] == chapter_no ){
for(var i = 0; i <= this['chapter_count']; i++; ){
$("ul").append("<li>Chapter Number"+i+"</li></br>")
}
};
})
});
});
Where chapter_no is extracted from url with window.location.search
Sample url: http://localhost:90/chapters.html?book_id=1
Thanks in advance.

Copy the below code in $.getJSON("files/js/books.json",function(data) function.
var selectedElement = $.grep(data.books, function( element, index ) {
if(chapter_no == element._id)
return element
});
for(var i =0 ; i<=selectedElement[0].chapter_count;i++)
{
$("ul").append("<li>Chapter Number"+i+"</li></br>")
}

first your json is not valid and have syntax error i think the true one is
json ={ "books": [ { "_id": "1", "book_cat": "OLD", "book_eng_name": "Book1",
"chapter_count": "50" }, { "_id": "2", "book_cat": "OLD",
"book_eng_name": "Book2", "chapter_count": "40" } ]}
its sample js code
json.books.forEach(function (b){
if(b._identer code here == "1")
{
for(var i =0 ; i<=b.caphter_count;i++)
{
//put your code here
}
}
})

Related

how to display data with javascript [object] [duplicate]

This question already has answers here:
How can I display a JavaScript object?
(40 answers)
Closed 3 years ago.
Please Help Me data does not appear in the div
result and display [object] how to fix it?
<div id="result">
</div>
<script>
jQuery(document).ready(function($){
var html = 'Sedang memproses data';
$('#result').html(html);
$('#result').css('background','none');
$.getJSON( "get.php?nopel=<?php echo $idp;?>", function(data) {
if(data) {
html = '<h2>Berikut Tagihan Listrik Anda</h2><table>';
$.each(data,function(x,y){
html += '<tr><td>'+x.replace('_','/')+'</td><td>'+y+'</td>';
});
html += '</table>';
$('#result').html(html);
}
else {
$('#result').html('Tidak ada data');
}
});
});
</script>
with json data like this, how to invite it to JavaScript
{
"status": "success",
"data": [
{
"Info": "A",
"hasil": "AA"
},
{
"Info": "B",
"hasil": "BB"
}
]
}
console.log (data)
Firstly, please don't use multiple accounts to ask the same question.
There are two main issues with your code...
As pointed out in comments by multiple people, if you want the dataproperty in your data json object, then you need to use data.data instead of data
The $.each function passes two parameters (index and value), but it appears that you think that it's passing the two properties of the object.
The below has the two changes, where you can see I've changed function(x,y) to function(i,v) where v is the object. I'm then using v.Info and v.hasil...
var data =
{
"status": "success",
"data": [
{
"Info": "A",
"hasil": "AA"
},
{
"Info": "B",
"hasil": "BB"
}
]
}
$(function(){
var html = 'Sedang memproses data';
$('#result').html(html);
$('#result').css('background','none');
//$.getJSON( "get.php?nopel=<?php echo $idp;?>", function(data) {
if(data) {
html = '<h2>Berikut Tagihan Listrik Anda</h2><table>';
$.each(data.data,function(i,v){
html += '<tr><td>'+v.Info.replace('_','/')+'</td><td>'+v.hasil+'</td>';
});
html += '</table>';
$('#result').html(html);
}
else {
$('#result').html('Tidak ada data');
}
//});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="result">
</div>

Create a single VCard file with multiple entries using javascript

I used the code from this github gist that allows you to save a single content into a VCF file.
<!doctype html>
<html>
<head>
<script type="text/javascript" src="vcard2.js"></script>
</head>
<script type="text/javascript">
// From JSON
var johnSmith = {
"version": "4.0",
"n": "SMITH;John;;",
"fn": "John Smith",
"nickname":"js",
"title": "Missing man too",
"tel": [
{"value": "555-555-555", "type": "cell"}
],
"email": [
{ "value": "john.smith#work.com", "type": "work" },
{ "value": "john.smith#home.com", "type": "home" }
]
}
var link = vCard.export(johnSmith, "John Smith", false) // use parameter true to force download
document.body.appendChild(link)
</script>
</body>
</html>
This worked for single content as file see JSfiddle.
My question is how to add multiple contents into same VCF file.
In the fiddle you provided just edit the dump() function to accept array. Then iterate the array and perform the exact same operations, combining the output (split with \n) into one variable.
dump: function(cards) {
var cardsLength = cards.length;
var cardsStr = "";
for (var cardsIndex = 0; cardsIndex < cardsLength; cardsIndex++) {
var card = cards[cardsIndex];
//...existing code... just remove the return
cardsStr+=str+"\n";
}
return cardsStr;
}
Now call vCard.export() and pass an array of objects instead of object.
Try it here: JSFiddle

Is it possible to access a json array element without using index number?

I have the following JSON:
{
"responseObject": {
"name": "ObjectName",
"fields": [
{
"fieldName": "refId",
"value": "2170gga35511"
},
{
"fieldName": "telNum",
"value": "4541885881"
}]}
}
I want to access "value" of the the array element with "fieldName": "telNum" without using index numbers, because I don't know everytime exactly at which place this telNum element will appear.
What I dream of is something like this:
jsonVarName.responseObject.fields['fieldname'='telNum'].value
Is this even possible in JavaScript?
You can do it like this
var k={
"responseObject": {
"name": "ObjectName",
"fields": [
{
"fieldName": "refId",
"value": "2170gga35511"
},
{
"fieldName": "telNum",
"value": "4541885881"
}]
}};
value1=k.responseObject.fields.find(
function(i)
{return (i.fieldName=="telNum")}).value;
console.log(value1);
There is JSONPath that lets you write queries just like XPATH does for XML.
$.store.book[*].author the authors of all books in the store
$..author all authors
$.store.* all things in store, which are some books and a red bicycle.
$.store..price the price of everything in the store.
$..book[2] the third book
$..book[(#.length-1)]
$..book[-1:] the last book in order.
$..book[0,1]
$..book[:2] the first two books
$..book[?(#.isbn)] filter all books with isbn number
$..book[?(#.price<10)] filter all books cheapier than 10
$..* All members of JSON structure.
You will have to loop through and find it.
var json = {
"responseObject": {
"name": "ObjectName",
"fields": [
{
"fieldName": "refId",
"value": "2170gga35511"
},
{
"fieldName": "telNum",
"value": "4541885881"
}]
};
function getValueForFieldName(fieldName){
for(var i=0;i<json.fields.length;i++){
if(json.fields[i].fieldName == fieldName){
return json.fields[i].value;
}
}
return false;
}
console.log(getValueForFieldName("telNum"));
It might be a better option to modify the array into object with fieldName as keys once to avoid using .find over and over again.
fields = Object.assign({}, ...fields.map(field => {
const newField = {};
newField[field.fieldName] = field.value;
return newField;
}
It's not possible.. Native JavaScript has nothing similar to XPATH like in xml to iterate through JSON. You have to loop or use Array.prototype.find() as stated in comments.
It's experimental and supported only Chrome 45+, Safari 7.1+, FF 25+. No IE.
Example can be found here
Clean and easy way to just loop through array.
var json = {
"responseObject": {
"name": "ObjectName",
"fields": [
{
"fieldName": "refId",
"value": "2170gga35511"
},
{
"fieldName": "telNum",
"value": "4541885881"
}]
}
$(json.responseObject.fields).each(function (i, field) {
if (field.fieldName === "telNum") {
return field.value // break each
}
})

parse json and output in html

I want to parse a json file and output in html by using javascript
here is my json file
{"quiz":[
{
"quizName":"Quiz 1",
"question": [
{
"text": "1+1?",
"choiceA": "1",
"choiceB": "2",
}
]
},
{
"quizName":"Quiz 2",
"question": [
{
"text": "2+2?",
"choiceA": "3",
"choiceA": "4",
}
]
}
]}
here is my html
<body>
<div id="placeholder"></div>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script>
$.getJSON('data.json', function(data) {
var output="<ul>";
for (var i in data.quiz) {
output+="<li>" + data.quiz[i].quizName+"</li>";
}
output+="</ul>";
document.getElementById("placeholder").innerHTML=output;
});
</script>
</body>
I want to display all the "quizName" in a list format like this
Quiz 1
Quiz 2
But by code doesn't output anything.
I am new to json and javascript, I don't know whether the json file is not correct or the javascript is not correct. Thanks.
You can't have commas after the last items of an object in a JSON file.
Change:
"choiceB": "2",
To this:
"choiceB": "2"
Do the same for choiceA": "4",
if u r not sure with the Json is right or wrong you can check here online json Parser or jsonEditor
you have extra commas
this is the correct Json
{"quiz":[
{
"quizName":"Quiz 1",
"question": [
{
"text": "1+1?",
"choiceA": "1",
"choiceB": "2"
}
]
},
{
"quizName":"Quiz 2",
"question": [
{
"text": "2+2?",
"choiceA": "3",
"choiceB": "4"
}
]
}
]}
ALso parsing it REFER parsing in fiddle
Hope this Helps
Remove extra commas in your json file at line numbers 9 and 19.
All you need it's do one more loop..
var output="<ul>";
for (var i in dataset) {
for (var j in dataset[i])
{
output+="<li>" + dataset[i][j].quizName+"</li>";
}
}
output+="</ul>";
document.getElementById("placeholder").innerHTML=output;
here you go: http://jsfiddle.net/baximilian/qpJjN/

Populate a variable using jQuery based on selections in a drop down

I'm trying to build a nested array in jQuery based on a user's selection from a drop down menu. This will be used in a JSON request at a later date.
So far my code does produce (almost) the required result, however no matter order i select the options from my drop down menu, the output (which i log in the console at the end) is always the same.
$('#comboGenre').change(function () {
var values = $('#comboGenre').val();
var parsedJSON = JSON.parse($data); //Data returned from ajax request
for (var i = 0; i < values.length; i += 1) {
$genreList = parsedJSON.genre[i];
console.log($genreList);
}
});
So if i select RPG and Action from my drop down, the output gives me RPG and Driving. If i selected RPG, Driving and Action (in that order), i get what i would expect RPG, Driving and Action.
So it's just iterating through my JSON, when really it should be returning the 'selected' option.
How can i achieve this?
My JSON looks like this if it's useful:
{"genres": [{
"genre": "RPG",
"publishers": [{
"publisher": "Square",
"games": [{
"game": "FFX",
"rating": [
12, 15
]
}]
}]
},
{
"genre": "Driving",
"publishers": [{
"publisher": "Turn10",
"games": [{
"game": "Forza",
"rating": [
5
]
}]
}]
},
{
"genre": "Action",
"publishers": [{
"publisher": "EA",
"games": [{
"game": "COD",
"rating": [
18, 20
]
}]
}]
}
]}
EDIT:
I've also tried this:
$('#comboGenre').change(function () {
var parsedJSON = JSON.parse($data);
$genreList = "";
$.each(parsedJSON.genres, function(index, value){
$genreList = parsedJSON.genres[index];
console.log($genreList);
});
});
And i end up getting ALL the objects in my JSON, so from here, i'm only wanting to add the selected object to the $genreList variable.
If you broke out some of the logic and created a genre finding function and used the selected string to find the proper object you could then put the object into the variable you will use later. I do some checking to ensure that the genre that has been selected isn't already in my array which is because I am using the multiple select
JSFiddle: http://jsfiddle.net/vkTFq/
Code:
$(function(){
var selectedGenres = [];
var genres =[{"genre":"RPG","publishers":[{"publisher":"Square","games":[{"game":"FFX","rating":[12,15]}]}]},{"genre":"Driving","publishers":[{"publisher":"Turn10","games":[{"game":"Forza","rating":[5]}]}]},{"genre":"Action","publishers":[{"publisher":"EA","games":[{"game":"COD","rating":[18,20]}]}]}]
$('#comboGenre').change(function() {
$(this).find(":selected").each(function() {
var selectedGenre = findGenre($(this).val())
if (!genreAlreadySelected(selectedGenre.genre)) {
selectedGenres.push(selectedGenre);
};
});
console.log (JSON.stringify(selectedGenres));
});
function genreAlreadySelected(genre){
for(var i = 0; i < selectedGenres.length; i++){
if (genre == selectedGenres[i].genre) {
return true;
};
return false;
}
}
function findGenre(genre){
for(var i = 0; i < genres.length; i ++){
console.log(genre)
if(genre == genres[i].genre){
return genres[i];
}
}
};
});

Categories

Resources