I cannot stop running into problems with this code. I figure I'm doing something monumentally wrong, and I figure asking people who know what they're doing would be the best thing to do.
The actual "problem" or assignment is to create a simple TV object. It has three characteristics. Make one. Call it. Display all the characteristics. Then it's done.
I declare variables and make a constructor. As per the rules of the assignment, both of these things must remain in the header of the document.
Next is the body. I want to create a new television object, called myTV, with those parameters. I create a function to recall the data back. Then I actively call the data back.
Somewhere along the lines I have logic problems, possible syntax problems, and who knows what else. My mind is reeling from staring at the same code for so long, so I'm going to grab something to drink and check back here in like 15. ugh.
<html>
<head>
<script type="text/javascript">
var manuTV;
var sizeTV;
var priceTV;
function Television(manu, size, price){
this.manuTV = manu;
this.sizeTV = size;
this.priceTV = price;
}
</script>
</head>
<body>
<script type="text/javascript">
var myTV = new Television("Sony", 52, 999);
function DisplayInfo(){
document.write("Television Manufacturer: " + this.manuTV + "<br />");
document.write("Size(in inches)" + this.sizeTV + "<br />");
document.write("Price:" + this.priceTV + "<br />");
}
myTV.displayInfo();
</script>
</body>
</html>
Your DisplayInfo method isn't related in any way to your Television. There are two easy things you can do to make it work. You can add DisplayInfo to Television's prototype.
Television.prototype.displayInfo = function(){
document.write("Television Manufacturer: " + this.manuTV + "<br />");
document.write("Size(in inches)" + this.sizeTV + "<br />");
document.write("Price:" + this.priceTV + "<br />");
}
This adds the method to Television's prototype so any Television can use it (tv.displayInfo()). You could also do it this way:
function displayInfo(tv){
document.write("Television Manufacturer: " + tv.manuTV + "<br />");
document.write("Size(in inches)" + tv.sizeTV + "<br />");
document.write("Price:" + tv.priceTV + "<br />");
}
Pass a Television object to DisplayInfo, (see the argument added to the method signature), then use tv instead of this. Then call the function like this:
displayInfo(myTv);
Related
I want to change the HTML content of my webpage from within a javascript function. My HTML looks like this:
<div class="chartInfo">
<p id="last_updated">Hello</p>
</div>
My Javascript function is a QueryResponse to a GoogleCharts query. It looks like this:
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
function function_1() {
var queryString = encodeURIComponent('SELECT AA, AB');
var query = new google.visualization.Query('https://docs.google.com/spreadsheets/d/1dXP9yGEzNlmRxwCr2kyMM9CcS5hloIxKvef0RSa10/gviz/tq?gid=559927965&headers=1&tq=' + queryString);
query.send(function_2);
};
function function_2(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
};
var data = response.getDataTable();
var t = (data.getvalue(0,0));
var latest_time = t.getDate()
document.getElementById("last_updated").innerHTML = "Last updated: " + latest_time;
};
</script>
Currently the webpage is showing "Hello" rather than "Last Updated: " + latest_time as I want it to.
I think it may be a problem of scope - when I write scripts out underneath I can change it from "Hello" to another string using document.getElementById, but then I can't access the variable latest_time which is within function_2.
Thanks in advance for any help!
Change dom.innerHTML to dom.textContent for changing text of it
I have a json.json file like this
{"name1":"Hallo","name2":"Defy","name3":"Carm","name4":"Disney"}
And this script im using to read the file
<script type='text/javascript'>
$(window).load(function(){
$.getJSON("json.json", function(person){
$.each(person, function(key, value)
{document.write(key+"= "+value+"<br />");
});
});
});
</script>
This script is made to poin out all of the data but i need only "name3" value to be stored to +value+
How to do that?
You dont need to iterate then:
$.getJSON("json.json", function(person){
document.write("name3=" person.name3);
});
I'd probably stray away from document.write and append to a container.
<div id="test"></div>
$.getJSON("json.json", function(person) {
$("#test").append("<span> name3= " + person.name3 + </span>");
});
$.getJSON provides the JavaScript object that is represented by the JSON it retrieves.
To access the name3 property of the object, as with any JavaScript Object, you can simply do:
$.getJSON("json.json", function(person){
// do whatever you want with person.name3...
console.log(person.name3);
}
To access to the property you just have to use " . ", so to get the name3 you have to do value.name3
There's no no need to use a foreach if you only have 1 item
<script type='text/javascript'>
$(window).load(function(){
$.getJSON("json.json", function(person){
document.write(key + " = " + value.name3 + "<br />");
});
});
</script>
I'm looking at this "for in" tutorial and I don't understand why I can't get the loop to write the aProperty value instead of just its name.
http://www.tutorialspoint.com/cgi-bi...=javascript_15
I've tried:
document.write(navigator.aProperty);
document.write(navigator + . + aProperty);
And various other forms, all have failed.
If I just code
document.write(navigator.onLine);
Why can't I make the var, "aProperty" work as a document.write parameter?
Thanks!
<script type="text/javascript">
<!--
var aProperty;
document.write("Navigator Object Properties<br /> ");
for (aProperty in navigator)
{
document.write(aProperty);
document.write("<br />");
}
document.write("Exiting from the loop!");
//-->
</script>
</body>
</html>
aProperty is, indeed, just the key. to return the value you need to ask navigator for it.
Add this in your for...in loop:
for (aProperty in navigator)
{
document.write(navigator[aProperty]);
document.write("<br />");
}
After getting my AJAX to work with help from another question I asked, I'd like to create another file that contains my functions to keep my code clean. I haven't found anything useful online, so I am thinking it might not be possible. Here is the code I'd like to extract:
<script> <!-- overall co2 -->
var co2;
var url="/solarpv/api/co2/list"
var jsonObject;
$(document).ready(function(){
$.getJSON(url,function(result){
jsonObject = result;
co2 = result[0].Cumulative_CO2;
$('#ajaxRequest').html("Our solar panels have saved " + co2 + " pounds of CO2 since they were installed.");
});
});
<!-- today co2 -->
var co2today;
var url2="/solarpv/api/co2/today"
$(document).ready(function(){
$.getJSON(url2,function(result){
co2today = result[0].CO2;
$('#today').html("Our Solar Panels have saved " + co2today + " pounds of c02 so far today.");
});
});
<!-- yesterday's CO2 -->
var url3 = "/solarpv/api/co2/list?start=2013-04-28%2001:00:00&end=2013-04-29%2001:00:00";
var yesterdayCO2;
$(document).ready(function(){
$.getJSON(url3,function(result){
yesterdayCO2 = result[0].Cumulative_CO2;
$('#yesterday').html("Yesterday alone, our solar panels saved the same amount of CO2 it would take " + yesterdayCO2/1.98 + " people to create!");
});
});
<!-- last years's CO2 -->
var url4 = "/solarpv/api/co2/list?start=2012-04-28%2001:00:00&end=2013-04-29%2001:00:00";
var trees;
$(document).ready(function(){
$.getJSON(url4,function(result){
trees = result[0].Cumulative_CO2;
$('#yesterday').html("Last year our solar panels saved the equivalent of " + trees/48.061 + " trees worth of C02");
});
});
</script>
An example of the html that would be left in the file that uses this looks like:
<li id="yesterday">
<script>
document.write("Yesterday alone, our solar panels saved the same amount of CO2 it would take " + yesterdayCO2 + " people to create!");
</script>
</li>
Use this tag to load the javascript. Put it at the bottom of your HTML just before </html>
<script type="text/javascript" src="myJs.js"></script>
Then you have to put the javascript (without the <script> tags) in the file named myJs.js and make it loadable from the browser.
I'm trying to reload a JSON file every 10 seconds with JQUERY.
The page is here: http://moemonty.com/chirp/chirp.html
The Code is here:
<html>
<head>
<title>the title</title>
<!-- included Jquery Library -->
<script type="text/javascript" src="./js/jquery-1.4.2.js"></script>
<!-- jquery library -->
</head>
<body>
<script>
$.ajaxSetup({ cache: false }); //disallows cachinge, so information should be new
function loadChirp(){ //start function
var url = "http://www.chirpradio.org/json";
$.getJSON("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%3D%22"+url+"%22&format=json&callback=?",
function(data){
console.log(data.query.results.json);
document.write('The artist is: ' + data.query.results.json.artist + '<br/><br/>');
document.write('The artist is: ' + data.query.results.json["record-label"] + '<br/><br/>' );
document.write('The album is: ' + data.query.results.json.album + '<br/><br/>');
document.write('The record label is: ' + data.query.results.json["record-label"] + '<br/><br/>');
document.write('The feedback link is: ' + data.query.results.json["feedback-link"] + '<br/><br/>');
document.write('The database id is: ' + data.query.results.json["database-id"] + '<br/><br/>');
document.write('The time is: ' + data.query.results.json.timestamp.time + ' ');
document.write(data.query.results.json.timestamp["am-pm"] + '<br/><br/>');
document.write('The current dj is: ' + data.query.results.json["current-dj"] + '<br/><br/>');
setTimeout("loadChirp()",5000);
alert('The timeout was triggered.');
});
} //end function
$(document).ready(function(){
//DOCUMENT READY FUNCTION
loadChirp();
});
//DOCUMENT READY FUNCTION
</script>
</body>
</html>
It doesn't seem to be working.
You probably want the previous set of returned data replaced by the new set, instead of appending it. In that case, using jQuery you can do:
<div id='content'></div>
<script>
function loadChirp(){
$.getJSON("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%3D%22"+url+"%22&format=json&callback=?",
function(data) {
$('#content').html('The artist is: ' + data.query.results.json.artist + '<br/><br/>');
});
setTimeout("loadChirp()",5000);
}
</script>
etc...
I would expect the loop to work as quoted, but there could be a subtlety around the fact you're using JSONP. I would change the setTimeout call to:
setTimeout(loadChirp, 5000);
...for a couple of reasons. First off, using the function reference rather than a code string is a better idea generally, and second off, you're quite certain that you're getting the right function reference (whereas with the string, what reference you get depends on the context in which the code is executed).
But as Pointy pointed out in a comment, there's a separate issue: document.write will not do what you probably want it to do there. You can only use document.write to write to the HTML stream that's being parsed as part of the original page load. After the page load, you can't use it anymore. Consider using jQuery's append or appendTo and similar functions to add to the DOM after page load.
You have an error in console.log(data.query.results.json); - console is not defined.
Also, you can use setInterval( "function()", 5000 );.
You should definitely use:
setInterval("loadChirp", 10000):
Don't write loadCrirp() inside setInterval as we're only passing a refrence