I am trying to store an image in a json object and display it on a html page with the rest of the data in the object. The image is stored locally in a folder called images. I have some code, but it doesnt seem to work... Can anyone please advise?
"photo":"<img src=images/audir8.jpg"
their is missing a closing ">" tag
Update you json like this
{
"id":2,
"name":"Audi A4",
"make":"Audi",
"model":"A4",
"enginesize":"1968cc",
"power":"140 BHP",
"acceleration":"7.8 seconds",
"topspeed":"139 MPH",
"drivetrain":"Front-wheel drive",
"specification":"Sat Nav, Heated Seats, Convertible, Immobiliser, Traction Control, Metallic paint, Airbags, LED lights",
"photo":"images/audir8.jpg"
}
html
<h1 id="title"></h1>
<ul>
<h2>Performance</h2>
<ul id="make"></ul>
<ul id="model"></ul>
<ul id="enginesize"></ul>
<ul id="power"></ul>
<ul id="acceleration"></ul>
<ul id="topspeed"></ul>
<ul id="drivetrain"></ul>
<ul id="specification"></ul>
<ul ><img id="photo" />
</ul>
</ul>
<script src="js/details.js"></script>
</div>
</div>
javascript
function populateContent(car)
{
titleEl=document.getElementById("title");
makeEL=document.getElementById("make");
modelEl=document.getElementById("model");
enginesizeEl=document.getElementById("enginesize");
powerEl=document.getElementById("power");
accelerationEl=document.getElementById("acceleration");
topspeedEl=document.getElementById("topspeed");
drivetrainEl=document.getElementById("drivetrain");
specificationEl=document.getElementById("specification");
photoEl=document.getElementById("photo");
//document.getElementById("imageid").src="../images/audir8.png";
titleEl.innerHTML = car.name;
makeEL.innerHTML = "<b>Make: </b>"+car.make;
modelEl.innerHTML = "<b>Model: </b>"+car.model;
enginesizeEl.innerHTML = "<b>Engine Size: </b>"+car.enginesize;
powerEl.innerHTML = "<b>Power: </b>"+car.power;
accelerationEl.innerHTML = "<b>0-60: </b>"+car.acceleration;
topspeedEl.innerHTML = "<b>Top Speed: </b>"+car.topspeed;
drivetrainEl.innerHTML = "<b>Drivetrain: </b>"+car.drivetrain;
specificationEl.innerHTML = "<h2>Specification: </h2>"+car.specification;
photoEl.src= car.photo;
}
You are missing the closing of image tag />. Add that and it will work. For demonstration I have used a live URL for the image. You can replace that with yours. Also, <ul> has <li> elements so replace that too.
var jsonData = {
"id":2,
"name":"Audi A4",
"make":"Audi",
"model":"A4",
"enginesize":"1968cc",
"power":"140 BHP",
"acceleration":"7.8 seconds",
"topspeed":"139 MPH",
"drivetrain":"Front-wheel drive",
"specification":"Sat Nav, Heated Seats, Convertible, Immobiliser, Traction Control, Metallic paint, Airbags, LED lights",
"photo":"<img src=http://myanmareiti.org/sites/default/files/styles/medium_retina/public/sample-5_0.jpg?itok=wn8qRWZM />"
};
function populateContent(car)
{
titleEl=document.getElementById("title");
makeEL=document.getElementById("make");
modelEl=document.getElementById("model");
enginesizeEl=document.getElementById("enginesize");
powerEl=document.getElementById("power");
accelerationEl=document.getElementById("acceleration");
topspeedEl=document.getElementById("topspeed");
drivetrainEl=document.getElementById("drivetrain");
specificationEl=document.getElementById("specification");
photoEl=document.getElementById("photo");
//document.getElementById("imageid").src="../images/audir8.png";
titleEl.innerHTML = car.name;
makeEL.innerHTML = "<b>Make: </b>"+car.make;
modelEl.innerHTML = "<b>Model: </b>"+car.model;
enginesizeEl.innerHTML = "<b>Engine Size: </b>"+car.enginesize;
powerEl.innerHTML = "<b>Power: </b>"+car.power;
accelerationEl.innerHTML = "<b>0-60: </b>"+car.acceleration;
topspeedEl.innerHTML = "<b>Top Speed: </b>"+car.topspeed;
drivetrainEl.innerHTML = "<b>Drivetrain: </b>"+car.drivetrain;
specificationEl.innerHTML = "<h2>Specification: </h2>"+car.specification;
photoEl.innerHTML = "<h2>photo: </h2>"+car.photo;
}
populateContent(jsonData);
<h1 id="title"></h1>
<ul>
<h2>Performance</h2>
<li id="make"></li>
<li id="model"></li>
<li id="enginesize"></li>
<li id="power"></li>
<li id="acceleration"></li>
<li id="topspeed"></li>
<li id="drivetrain"></li>
<li id="specification"></li>
<li id="photo"></li>
</ul>
Related
I'm working with JavaScript and HTML and I would like to be able to add user input to a multilevel list in HTML. I have started by making a multilevel list in HTML. As an example I have made a list with Dog information.
<div>
<h3> Dogs </h3>
<ul id="myList">
<li><b>Dog Breeds</b>
<ul>
<li class="facts"> There are a approximately 340 recognized breeds.</li>
</ul>
</li>
<li><b>Dog Fur</b>
<ul>
<li class="facts"> Depending on the dogs, there are a lot of different kinds of fur.</li>
</ul>
</li>
</ul>
</div>
Underneath this list I have made 2 fields which can hold userinput and a button next to it which can add the typed in information to the list. My code for the button and type fields is the following:
<input type='text' id='input' placeholder="Title"/>
<button type="button" id="add">Add new dog fact</button><br>
<textarea id="input2" rows="5" cols="18" placeholder="The dog fact.."></textarea>
In order to add the input to the list, I have written this piece of code:
"myList" is the id I have given the unordered list.
document.getElementById("add").onclick = function() {
var title = document.getElementById("input").value;
var description = document.getElementById("input2").value;
var li = document.createElement("li");
li.textContent = title + description;
document.getElementById("myList").appendChild(li);
document.getElementById("input2").value = ""; // clears the value
document.getElementById("input").value = ""; // clears the value
My problem now, is that it will not be structured as I would like.
By using the code above, the output will be as following if I type in "Dog Size" as title and "Dogs can be both large and small." as the description:
Dog SizeDogs can be both large and small.
instead of:
Dog Size
Dogs can be both large and small.
Does anyone know how to change this, so the user input will be structured the same way the rest of the list is? So that the description will be nested within the title? I'm aware that it is because I have defined "li.textContent" as "title + description", I just don't know how else to add the description data. I have tried to create 2 new list elements in the javaScript code, but this just, as expected, creates 2 new list elements and then I tried to style the description-element with "title.style.listStyleType = "none";", but if I place it in the function, then the entire functions stops working. I'm very confused, and if anyone is able to help me I would be very grateful! Thank you :)
use innerHTML and add <br> between title and description.
document.getElementById("add").onclick = function() {
var title = document.getElementById("input").value;
var description = document.getElementById("input2").value;
var li = document.createElement("li");
li.innerHTML = title + "<br>" + description;
document.getElementById("myList").appendChild(li);
document.getElementById("input2").value = "";
document.getElementById("input").value = "";
}
<div>
<h3> Dogs </h3>
<ul id="myList">
<li><b>Dog Breeds</b>
<ul>
<li class="facts"> There are a approximately 340 recognized breeds.</li>
</ul>
</li>
<li><b>Dog Fur</b>
<ul>
<li class="facts"> Depending on the dogs, there are a lot of different kinds of fur.</li>
</ul>
</li>
</ul>
</div>
<input type='text' id='input' placeholder="Title" />
<button type="button" id="add">Add new dog fact</button><br>
<textarea id="input2" rows="5" cols="18" placeholder="The dog fact.."></textarea>
</div>
Instead of using onclick, use addEventListener and if you want to add the description(as ul) under the title, below is the code.
const list = document.querySelector('#myList');
document.querySelector('button#add')
.addEventListener('click', function() {
const title = document.querySelector('#input').value;
const description = document.querySelector('#input2').value;
const li = document.createElement('li');
li.innerHTML = `<b>${title}</b>`;
const ul = document.createElement('ul');
const childli = document.createElement('li');
childli.textContent = description;
ul.appendChild(childli);
li.appendChild(ul);
list.appendChild(li);
});
<div>
<h3> Dogs </h3>
<ul id="myList">
<li><b>Dog Breeds</b>
<ul>
<li class="facts"> There are a approximately 340 recognized breeds.</li>
</ul>
</li>
<li><b>Dog Fur</b>
<ul>
<li class="facts"> Depending on the dogs, there are a lot of different kinds of fur.</li>
</ul>
</li>
</ul>
</div>
<input type='text' id='input' placeholder="Title" />
<button type="button" id="add">Add new dog fact</button><br>
<textarea id="input2" rows="5" cols="18" placeholder="The dog fact.."></textarea>
I am currently trying to randomize the ads that show up on this website with JavaScript. In order to do this I am importing two script files.
The issue is I can not get the image to load, and I am unsure as to whether it's a problem with the parameters I have set or an error in the format of "" and '' when trying to output the element. I have already attempted to preset the variable that belongs as the url with no luck. The line code I tried with this attempt was var img = "ad" + rNumber + ".jpg"; Below is the HTML code with the embedded JavaScript that I am working on. Any help with this problem would be greatly appreciated.
function randInt(n) {
randNum = Math.ceil(Math.random() * n);
return randNum;
}
function adDescription(n) {
var descrip = new Array();
descrip[1] = "[AD] Diamond Health Club - For all your Health Club Needs";
descrip[2] = "[AD] Pixal - Quality Digital Equipment and Accessories";
descrip[3] = "[AD] dHome - Quality Geodesic Domes and Homes";
descrip[4] = "[AD] Dunston Retreat Center - get away";
descrip[5] = "[AD] LanGear - Quality Network Solutions for all your Business Needs";
return descrip[n];
}
function adLink(n) {
var link = new Array();
link[1] = "http://www.diamondhealth.com";
link[2] = "http://www.pixalproducts.com";
link[3] = "http://www.dhome.com";
link[4] = "http://www.dunstonretreats.com";
link[5] = "http://wwww.langearproducts.com";
return link[n];
}
<html>
<head>
<!--
New Perspectives on HTML and CSS
Tutorial 10
Case Problem 2
The Ridgewood Herald Tribune
Author: Brigitte Arcoite
Date: 7-31-17
Filename: front.htm
Supporting files: ads1.jpg - ads5.jpg, ads.js, fp.jpg, logo.jpg,
modernizr-1.5.js, random.js, styles.css
-->
<meta charset="UTF-8" />
<title>The Ridgewood Herald Tribune</title>
<script src="modernizr-1.5.js"></script>
<link href="styles.css" rel="stylesheet" type="text/css" />
<script src="random.js" type="text/javascript"></script>
<script src="ads.js" type="text/javascript"></script>
</head>
<body>
<nav>
<h1>Contents</h1>
<p class="section">Main</p>
<ul>
<li>Home</li>
<li>Subscriptions</li>
<li>Contact Us</li>
<li>News Sources</li>
</ul>
<p class="section">News</p>
<ul>
<li>Local</li>
<li>National</li>
<li>International</li>
</ul>
<p class="section">Sports</p>
<ul>
<li>Baseball</li>
<li>Basketball</li>
<li>Football</li>
<li>Golf</li>
<li>Hockey</li>
<li>Miscellaneous</li>
</ul>
<p class="section">Opinion</p>
<ul>
<li>Editorials</li>
<li>Columnists</li>
<li>Letters</li>
</ul>
<p class="section">Classifieds</p>
<ul>
<li>Employment</li>
<li>For Sale</li>
<li>Personals</li>
<li>Real Estate</li>
<li>Wanted</li>
</ul>
<p class="section">Other</p>
<ul>
<li>Business</li>
<li>Weather</li>
<li>Entertainment</li>
</ul>
</nav>
<section>
<div id="ads">
<script>
var rNumber = randInt(5); //generate a random integer from 1 to 5
var rAd = adDescription(descrip[rNumber]); //description of the random ad
var rLink = adLink(link[rNumber]); //url of the random ad
var img = "ad" + rNumber + ".jpg";
alert(rNumber);
document.write("<a href='" + rLink + "'>");
document.write("<img src='" + img + "' alt='" + rAd + "' />");
document.write("</a>");
</script>
</div>
<div id="request">Contact us today to place your ad</div>
<header><img src="logo.jpg" alt="Ridgewood Herald Tribune" /></header>
<img src="fp.jpg" alt="" id="fp" />
<h2>Park Opens</h2>
<p>The <i>Adventure Island</i> theme park opened its doors on Monday near Ridgewood. The park, one of the biggest in New Jersey, drew large crowds, but the long lines didn't deter anyone. "I've been watching them put up the rides over the last year,
it's really exciting to finally get inside the gates!" said Ridgewood resident Denise Brooks.
</p>
<p class="cont">story continues on page 2...</p>
<footer>
<address>
<b>Ridgewood Herald Tribune</b> ° 10010 Atwood Ave.
° Ridgewood, NJ 07451<br />
Phone: (201)555-1101 ° Fax: (201)555-1102
</address>
</footer>
</section>
</body>
</html>
Your variable randNum isn't defined. You're also getting the ol' Uncaught Reference error (randInt [function] not defined). Perhaps add an event listener to your scripts to ensure they run when the DOM Content is loaded
<script>
document.addEventListener("DOMContentLoaded", function(event) {
//console.log("DOM fully loaded and parsed");
do stuff here
});
</script>
Hope this helps
Alright so I've been messing around with this for 2 days and can't figure it out for the life of me. Basically I have dynamically generated <li> entries appending to a static <ul>, and then calling the .listview('refresh',true) function afterwards.
The first generation is fine, the second generation screws up the padding on the already listed elements, but shows the newly listed elements just fine.
I also have a "show more" button that retrieves these dynamically generated entries, and then updates itself to reflect a new offset. So here is the code.
HTML:
<div data-role="page" id="librarysearch" data-theme="a">
<div data-role="header" data-position="inline"></div>
<div data-role="content">
<div>
Finished
Playlist
<input id="librarysearchinput" size="60" onkeypress="if (event.keyCode == 13) applib.searchlibraryservers();" type="search" />
<a href="javascript:applib.searchlibraryservers();" data-icon="search" data-inline="true" data-role=button>Search</a>
<ul data-role="listview" id="libraryartistresults" name="libraryartistresults" data-theme="a"></ul>
<div id="showmoreartists"></div>
</div>
</div>
<div data-role="footer" data-position="inline">
</div>
Initial Generation of list elements:
this.searchlibraryservers = function(offset)
{
window.$("#librarysearchinput").blur();
var query = window.$("#librarysearchinput").val();
if (query !== "")
{
if (sonicservers.length > 0)
{
if (!libraryisdynamic)
libraryserverid = selectedsonicserverid;
remoteapp.searchserver(libraryserverid, query + "*", {songCount: 51}, function(results)
{
var htmlout = "";
var buttonhtml = "";
if (results && results.success)
{
var i;
librarysearchresults = results.response;
htmlout += "<li data-role=\"list-divider\">Artists</li>";
for (i in librarysearchresults.artists)
htmlout += "<li><a href='javascript:applib.libraryartist(" + librarysearchresults.artists[i].id + ");'>" + librarysearchresults.artists[i].name + "</a></li>";
if (countProperties(librarysearchresults.artists) > 1) // just set to 1 for testing
buttonhtml += "Show More";
window.$("#libraryartistresults").append(htmlout);
window.$("#libraryartistresults").listview('refresh', true);
window.$("#showmoreartists").html(buttonhtml).trigger('create');
}
});
}
}
};
This generates the following html:
<li data-role=\"list-divider\">Artists</li>
<li><a href='javascript:applib.libraryartist(7);'>Christian Altenburger, violin, German Bach Soloists, Helmut Winschermann</a></li>
<li><a href='javascript:applib.libraryartist(14);'>Eckart Haupt, flute; Bach Collegium Musicum, Max Pommer</a></li>
<li><a href='javascript:applib.libraryartist(15);'>New Bach Collegium Musicum, Max Pommer</a></li>
<li><a href='javascript:applib.libraryartist(16);'>Burchard Glaetzner, oboe; New Bach Collegium Musicum, Max Pommer</a></li>
<li><a href='javascript:applib.libraryartist(81);'>John Elwes, David Thoma, Bach Collegium Japan and Masaaki Suzuki</a></li>
<li><a href='javascript:applib.libraryartist(125);'>1734 Bach</a></li>
<li><a href='javascript:applib.libraryartist(131);'>1731 Bach</a></li>
And for the button:
Show More
This all seems fine, and in fact shows up fine, but when I click show more it basically does the same thing as the initial result except taking the offset into account:
this.showmoreartists = function(query, offset)
{
var htmlout = "";
var buttonhtml = "";
remoteapp.searchserver(selectedsonicserverid, query + "*", {artistOffset: offset}, function(results)
{
librarysearchresults = results.response;
for (var i in librarysearchresults.artists)
htmlout += "<li><a href='javascript:applib.libraryartist(" + librarysearchresults.artists[i].id + ");'>" + librarysearchresults.artists[i].name + "</a></li>";
if (countProperties(librarysearchresults.artists) > 1) //just set to 1 for testing
{
buttonhtml += "Show More";
}
else
{
window.$("#showmorebutton").hide();
}
window.$("#showmoreartists").html(buttonhtml).trigger('create');
window.$("#libraryartistresults").append(htmlout);
window.$("#libraryartistresults").listview('refresh', true);
});
};
The newly generated html that it appends to "libraryartistresults" seems fine, (the results are the same due to the testing setup, it should be a moot point for this problem though since the listview shouldn't care about it being the same.
<li><a href='javascript:applib.libraryartist(7);'>Christian Altenburger, violin, German Bach Soloists, Helmut Winschermann</a></li>
<li><a href='javascript:applib.libraryartist(14);'>Eckart Haupt, flute; Bach Collegium Musicum, Max Pommer</a></li>
<li><a href='javascript:applib.libraryartist(15);'>New Bach Collegium Musicum, Max Pommer</a></li>
<li><a href='javascript:applib.libraryartist(16);'>Burchard Glaetzner, oboe; New Bach Collegium Musicum, Max Pommer</a></li>
<li><a href='javascript:applib.libraryartist(81);'>John Elwes, David Thoma, Bach Collegium Japan and Masaaki Suzuki</a></li>
<li><a href='javascript:applib.libraryartist(125);'>1734 Bach</a></li>
<li><a href='javascript:applib.libraryartist(131);'>1731 Bach</a></li>
The button html looks fine too:
Show More
I've even tried using the "style="white-space:normal;" in the UL.
TL:DR here's the code I believe to have the most relevance
STATIC HTML:
<ul data-role="listview" id="libraryartistresults" name="libraryartistresults" data-theme="a"></ul>
<div id="showmoreartists"></div>
HTML UPDATE:
window.$("#showmoreartists").html(buttonhtml).trigger('create');
window.$("#libraryartistresults").append(htmlout);
window.$("#libraryartistresults").listview('refresh', true);
GENERATED HTML SAMPLE:
<li><a href='javascript:applib.libraryartist(125);'>1734 Bach</a></li>
<li><a href='javascript:applib.libraryartist(131);'>1731 Bach</a></li>
It's probably some simple oversight but at this point I'm stuck. I'll keep digging around, maybe the append is placing the <li> after the </ul>
And thanks for reading this if you did, it was a long post I know and I appreciate you taking the time to just get through it all.
Well I'll be damned...the answer was extremely simple:
Change window.$("#libraryartistresults").listview('refresh', true);
to: window.$("#libraryartistresults").listview('refresh');
So...not sure if it's due to jQM 1.2, or some weird stuff going on with my framework or something but it fixed it 100%.
I'd like to give a special thanks to ezanker for taking his time to analyze and write up a JSFiddle example for me to work with.
I want to load a JSON file that creates a list inside a Bootstrap Modal. I have it set where if you click on a person's picture, the modal pops up.
<li class="project span3" data-type="pfa">
<a data-toggle="modal" data-target="#myModal" class="thumbnail">
<img src="img/anon.jpg" alt="Kenneth Atkins" />
<h1>Kenneth Atkins</h1>
<p>[Description here]</p>
</a>
</li>
Here's an example of the JSON data:
var florida_exoneration = [
{
"last_name":"Atkins",
"first_name":"Kenneth",
"age":16,
"race":"Caucasian",
"state":"FL",
"crime":"Sexual Assault",
"sentence":"10 years",
"conviction":2004,
"exonerated":2008,
"dna":"",
"mistaken witness identification":"",
"false confession":"",
"perjury/false accusation":"Y",
"false evidence":"",
"official misconduct":"",
"inadequate legal defense":"",
"compensation":""
}
]
I'd like the modal to display something like this inside the box:
Title = "first_name + last_name"
Age = "age"
Race = "race"
State = "state"
""
""
I also want to make sure the data is tied to the picture so the modal doesn't get confused. I'm sorry if this is a bit confusing. I'll try and clarify if anyone has any questions.
Method 1: using Ajax
Every time a user clicks an image, you get the id from the clicked image and then you send an Ajax request to server in order to get the JSON object.
HTML
<ul>
<li class="project span3" data-type="pfa">
<a href="#" data-id="2" class="thumbnail">
<img src="img/anon.jpg" alt="Kenneth Atkins" />
<h1>Kenneth Atkins</h1>
<p>[Description here]</p>
</a>
</li>
</ul>
JavaScript
(function($) {
var infoModal = $('#myModal');
$('.thumbnail').on('click', function(){
$.ajax({
type: "GET",
url: 'getJson.php?id='+$(this).data('id'),
dataType: 'json',
success: function(data){
htmlData = '<ul><li>title: '+data.first_name+'</li><li>age: '+data.age+'</li></ul>';
infoModal.find('.modal-body').html(htmlData);
infoModal.modal('show');
}
});
return false;
});
})(jQuery);
Method 2: using hidden div
No need to any Ajax request, but you need to create a hidden div that contain all the information you want to display in the modal
HTML
<ul>
<li class="project span3" data-type="pfa">
<a href="#" class="thumbnail">
<img src="img/anon.jpg" alt="Kenneth Atkins" />
<h1>Kenneth Atkins</h1>
<p>[Description here]</p>
<div class="profile hide">
<ul>
<li>title: Atkins Kenneth</li>
<li>Age: 16</li>
</ul>
</div>
</a>
</li>
</ul>
JavaScript
(function($) {
var infoModal = $('#myModal');
$('.thumbnail').on('click', function(){
htmlData = $(this).find('.profile').html();
infoModal.find('.modal-body').html(htmlData);
infoModal.modal('show');
return false;
});
})(jQuery);
I am using this plugin for ratings (http://wbotelhos.com/raty/). Basically, I am displaying multiple items, each item has its own rating stars. The problem is, it is only displaying the first result which is '2.3' and then apply it to all remaining items. How can I fix this?
<ul>
<li>
<div class="num_ratings">2.3</div>
<p class="rating-stars"></p>
</li>
<li>
<div class="num_ratings">4.1</div>
<p class="rating-stars"></p>
</li>
<li>
<div class="num_ratings">3.0</div>
<p class="rating-stars"></p>
</li>
<li>
<div class="num_ratings">3.3</div>
<p class="rating-stars"></p>
</li>
</ul>
<script>
$.fn.raty.defaults.path = 'img';
rating = parseInt($('.num_ratings').html());
$('.rating-stars').raty(
{
width: 112,
readOnly : true,
score: rating,
});
</script>
Try it like this:
$.fn.raty.defaults.path = 'img';
$("li").each(function(){
rating = $('.num_ratings' , this).text();
$('.rating-stars' , this).raty(
{
width: 112,
readOnly : true,
score: rating,
});
});
In this way it will run on every li , get its num_ratings data and create rating in its specific rating-stars p.