I'm attempting to complete and exercise from the JavaScript Bible, and am having trouble getting my script to function.
The assignment is to create a page that allows users to query a planet's name, and, via a script that matches the planet's name with its data stored in the associate arrays, call up its distance and diameter information.
I'm attempting to call the function 'getPlanetInfo' via a button (onclick='getPlanetInfo()'). However, my error console reports that it cannot find a variable named 'getPlanetInfo' when I attempt to run it.
I've attached both my JS and HTML code below. Any idea as to why my function isn't being properly called would be hugely appreciated.
HTML:
<!DOCTYPE html>
<html>
<head>
...
<script type="text/javascript" src="planets.js"></script>
</head>
<body>
<h1>Check a planet's distance from the sun and its diameter!</h1>
<form>
<input type="text" name="entry" id="entry">
<input type="button" value="Check it!" onClick="getPlanetInfo()">
</form>
</body>
</html>
JS:
var planetNames = new Array(4);
planetNames[0] = "Mercury";
planetNames[1] = "Venus";
planetNames[2] = "Earth";
planetNames[3] = "Mars";
var planetDistances = new Array(4);
planetDistances[0] = "36 million miles";
planetDistances[1] = "67 million miles";
planetDistances[2] = "93 million miles";
planetDistances[3] = "141 million miles";
var planetDiameters = new Array(4);
planetDiameters[0] = "3,100 miles";
planetDiameters[1] = "7,700 miles";
planetDiameters[2] = "7,920 miles";
planetDiameters[3] = "4,200 miles";
function getPlanetInfo()
{
var selectedPlanet = document.getElementById("entry").value;
for (var i = 0; i < planetNames.length; i++)
{
if (planetNames[i] == selectedPlanet)
{
break;
}
}
if (i < planetNames.length)
{
alert(selectedPlanet + " is " + planetDistances[i] " in distance from the Sun and " + planetDiameters[i] + "in diameter.")
}
else
{
alert("Sorry, " + selectedPlanet + " isn't in the database.");
}
}
This line:
alert(selectedPlanet + " is " + planetDistances[i] " in distance from the Sun and " + planetDiameters[i] + "in diameter.")
is missing a + sign after planetDistances[i], so the function has a syntax error and is not created, and naturally it's not found when called.
http://www.jsfiddle.net helps you create a reproducible case that we can all see, use it when you need to ask js questions.
You're missing a + - this:
alert(selectedPlanet + " is " + planetDistances[i] " in distance from the Sun and " + planetDiameters[i] + "in diameter.")
should be
alert(selectedPlanet + " is " + planetDistances[i] + " in distance from the Sun and " + planetDiameters[i] + "in diameter.")
You should use something like Firebug to catch syntax errors when loading your script.
Related
For example, there is a page like below.
<html>
<head>
<title>Variables!!!</title>
<script type="text/javascript">
var lookatthis = 11;
var one = 22;
var two = 3;
var add = one + two;
var minus = one - two;
var multiply = one * two;
var divide = one/two;
document.write("First No: = " + one + "<br />Second No: = " + two + " <br />");
document.write(one + " + " + two + " = " + add + "<br/>");
document.write(one + " - " + two + " = " + minus + "<br/>");
document.write(one + " * " + two + " = " + multiply + "<br/>");
document.write(one + " / " + two + " = " + divide + "<br/>");
</script>
</head>
<body>
</body>
</html>
I want to assign the javascript variable "lookatthis" on debug console.
//apologise for my ambiguous question. I would rather say,
"I want to assign new value to variable "lookatthis" on this web-page using console on explorer."
Thank you for your kind teaching.)
Open debug console and write there:
lookatthis = 20
But this get you nothing
You can use the log method:
console.log(lookatthis);
Anywhere in your script block after your initial assignment of lookatthis, you can write the value to the console with the command:
console.log(lookatthis);
You achieve it by using prompt function
var lookatthis = prompt('Type the lokaltthis value');
If what you want is to be able to 'set' the value of lookatthis, you can use an input and using jquery or pure js get the value of the input and assign it to 'lookatthis'.
Edit: You can also use in the chrome console: lookatthis=25
but as your script loads when page loads, changes will not be shown but the value will be changed
I am making a food delivery app. I would like that there would be a place whereby it would display the total. Right now, I am unable to display the total amount from multiplying quantity and price. It does not show up on the app.
And, there are no errors on the console too.
Javascript Code:
function _showorderResult(arr) {
var value1 = arr[0].price;
var value2 = arr[0].quantity;
for (var i = 0; i < arr.length; i++) {
result = value1 * value2;
htmlstring = "";
$("#itemimage").html("<img src='" + serverURL() + "/images/" +
arr[i].imagefile + "' width='200'>");
$("#price").html("Price" + ": " + " $" + arr[i].price);
$("#itemname").html("Item" + ":" + arr[i].itemName);
$("#quantity").html("Quanitiy" + ":" + arr[i].quantity);
$("result").append(htmlstring);
$("#requestedDateTime").html("To delivery by" + ":" + arr[i].requestedDateTime);
$("#deliveredDateTime").html("Delivered on" + ":" + arr[i].deliveredDateTime)
}
}
And, there are no errors on the console too.
There were plenty of errors in my console, but there are several mistakes here. The first is that your code is not runnable. Please consider making a minimal, verifiable example.
Next, you are misusing or not properly formatting the append(...) function. That's intended to append HTML elements, not string values.
As the comments suggest, you seem to have confused var result and $("result"). If you're not using the DOM selector, you probably don't want to jQuery-wrap your variables. The proper jQuery-wrap syntax would have been $(result) without the double quotes, but please don't do that either, it doesn't offer any benefit over just var result. htmlstring doesn't contain any actual HTML, so I've renamed it runningTotal instead and add it to the price * quantity. This must be initialized first or you'll get NaN.
Make sure to initialize your variables. To this point, there's some hard-coded indexes such as value1 = arr[0].price which make no sense in this pasted code. We can assume you left these here after troubleshooting. Please clean them up next time.
Finally, this is minor, but be consistent with your object names... e.g. imagefile versus imageFile. It doesn't matter which you choose so as long as you're consistent. This will help find typos down the road.
Here's a working example:
<html>
<img src="" id="itemimage">
<p id="price">Price: $0.00</p>
<p id="itemname">Item: None</p>
<p id="quantity">Quantity: None</p>
<p id="result">Running: None</p>
<p id="requestedDateTime">To delivery by: None</p>
<p id="deliveredDateTime">Delivered on: None</p>
<script>
var order = [{
price: 5,
quantity: 3,
itemName: 'Pizza',
imagefile: 'pizza.png',
requestedDateTime: '12:00',
deliveredDateTime: '12:30'
}];
/** Dummy function to allow code to run **/
var serverURL = function() { return ""; }
function _showorderResult(arr) {
// var value1 = arr[0].price;
// var value2 = arr[0].quantity;
var result;
var runningTotal = 0;
for (var i = 0; i < arr.length; i++) {
result = arr[i].price * arr[i].quantity;
runningTotal += result;
$("#itemimage").html("<img src='" + serverURL() + "/images/" + arr[i].imagefile + "' width='200'>");
$("#price").html("Price" + ": " + " $" + arr[i].price);
$("#itemname").html("Item" + ":" + arr[i].itemName);
$("#quantity").html("Quanitiy" + ":" + arr[i].quantity);
$("#result").html("Running" + ":" + runningTotal);
$("#requestedDateTime").html("To delivery by" + ":" + arr[i].requestedDateTime);
$("#deliveredDateTime").html("Delivered on" + ":" + arr[i].deliveredDateTime);
}
}
_showorderResult(order);
</script>
</html>
I'm trying to essentially set up a button that will either copy a bunch of text that will get output to a document.getelementbyid output to help me out while at work. This is what I have so far for the output and everything works, but would love to have a button that will automatically highlight everything taken from all my input fields.
function display(){
var caller = document.getElementById("form1").value;
var ctn = document.getElementById("form2").value;
var fan = document.getElementById("form3").value;
var business = document.getElementById("form4").value;
var requestor = document.getElementById("form5").value;
var reason = document.getElementById("form6").value;
document.getElementById("output").innerHTML = "form1: " + form1 + "<br>form2: " + form2 + "<br>form3: " + form3 + "<br>form4: " + form4 + "<br>form5: " + form5 + "<br>form6: " + form6;
}
This feeds data from my input fields at the top (naturally they have different names and labels in the document, just can't copy anything proprietary here). The below codes are the button code and the paragraph code to display it when I click so that it appears on the page for me to select.
<button onclick="display();" style="width: 50px; background-color:#3ea055">Submit</button>
<p id="output"></p>
I've tried several different snippets of code online to get it to either select or copy or whatever, and it isn't working.
you dont have variables named form1 form2 etc., in the output area I've changed the values to your variable names try this
function display(){
var caller = document.getElementById("form1").value;
var ctn = document.getElementById("form2").value;
var fan = document.getElementById("form3").value;
var business = document.getElementById("form4").value;
var requestor = document.getElementById("form5").value;
var reason = document.getElementById("form6").value;
document.getElementById("output").innerHTML = "form1: " + caller + "<br>form2: " + ctn + "<br>form3: " + fan + "<br>form4: " + form4 + "<br>form5: " + requestor + "<br>form6: " + form6;
}
In the line where you print the values to the output element you need to use the variables you just filled.
document.getElementById("output").innerHTML = "form1: " + caller + "<br>form2: " + ctn+ "<br>form3: " + fan + "<br>form4: " + business + "<br>form5: " + requestor + "<br>form6: " + reason;
I apologize in advance if I'm vague or my code is difficult to understand, I'm still learning this stuff. I'm trying to display information that is stored within an array. I want to display this information when a button is clicked and when it is clicked again, the next index in the array displays its information..
I need help setting up a function that advances to the next index of the array. Thanks!
(function(){
var students =[ //array of information
{name:'john',
address:{
address:'821 Imaginary St',
city:'Chicago',
state:'Il'},
gpa:[4.0,3.5,3.8]},
{name:'jim',
address:{
address:'127 fake Rd',
city:'Orlando',
state:'Fl'},
gpa:[2.5,3.3,3.6]}];
var redBut = document.querySelector('.buttonred');
redBut.onclick = getInfo;
var count = 0;
function getInfo(){
var stn = students[0];
if(count<3){
count++;
document.getElementById('name').innerHTML = 'Name: ' + stn.name; //this is what is to be displayed when the button is clicked
document.getElementById('address').innerHTML = 'Address: ' + stn.address.address + " " + stn.address.city + ", " + stn.address.state;
document.getElementById('gpa').innerHTML = 'GPA: ' + stn.gpa[0] +", " + stn.gpa[1] + ", " + stn.gpa[2];
document.getElementById('date').innerHTML = 'Date: ' + d.toLocaleDateString();
document.getElementById('gpaavg').innerHTML = 'Average GPA: ' + gpas;
}
}
I think you want: var stn = students[count];
And not: var stn = students[0];
(DOH!)
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
I'm trying to create a calculator in javascript for inverse trigonometry functions (arcsine, arccosine, arctangent) and I have it so there are checkboxes for each input so window.alert doesn't return NULL (user-friendly).
The Form:
<form name="inverse">
<legend>Legend is here.</legend>
<input type="checkbox" name="inverse-cb1" value="sine"></input><label> sin<sup>-1</sup> ( </label><input type="text" size=5 name="sin"><label> )</label><br>
<input type="checkbox" name="inverse-cb2" value="cosine"></input><label> cos<sup>-1</sup> ( </label><input type="text" size=5 name="cos"><label> )</label><br>
<input type="checkbox" name="inverse-cb3" value="tangent"></input><label> tan<sup>-1</sup> ( </label><input type="text" size=5 name="tan"><label> )</label><br>
<br><input type="button" onclick="trigI()" value="Calculate">
</form>
The script:
function trigI(){
var sin = document.inverse.sin.value; //sine
var cos = document.inverse.cos.value; //cosine
var tan = document.inverse.tan.value; //tangent
var sin1 = Math.asin(sin); //arcsine
var cos1 = Math.acos(cos); //arccosine
var tan1 = Math.atan(tan); //arctangent
var sin1d = sin1 * (180/Math.PI); //convert radians to degrees (sine)
var cos1d = cos1 * (180/Math.PI); //convert radians to degrees (cosine)
var tan1d = tan1 * (180/Math.PI); //convert radians to degrees (tangent)
if (isNaN(sin) || isNaN(cos) || isNaN(tan) ){
window.alert("Please input a number.");
return;
}
if (!document.inverse.inverse-cb1.checked){ //no sine input
window.alert("When cos(\u2220) = " + cos + " and tan(\u2220) = " + tan + " :" + "\n\n" + "cos\u2212\u00B2(A) = " + cos1d + "\n" + "tan\u2212\u00B2(A) = " + tan1d + "\u00B0");
return;
}
if (!document.inverse.inverse-cb2.checked){ //no cosine input
window.alert("When sin(\u2220) = " + sin + " and tan(\u2220) = " + tan + " :" + "\n\n" + "sin\u2212\u00B2(A) = " + sin1d + "\u00B0" + "\n" + "tan\u2212\u00B2(A) = " + tan1d + "\u00B0");
return;
}
if (!document.inverse.inverse-cb3.checked){ //no tangent input
window.alert("When sin(\u2220) = " + sin + " and cos(\u2220) = " + cos + " :" + "\n\n" + "sin\u2212\u00B2(A) = " + sin1d + "\u00B0" + "\n" + "cos\u2212\u00B2(A) = " + cos1d + "\u00B0");
return;
}
if (!document.inverse.inverse-cb1.checked && !document.inverse.inverse-cb2.checked){ //no sine and cosine input
window.alert("When tan(\u2220) = " + tan + " :" + "\n\n" + "tan\u2212\u00B2(A) = " + tan1d + "\u00B0");
return;
}
if (!document.inverse.inverse-cb2.checked && !document.inverse.inverse-cb3.checked){ //no cosine and tangent input
window.alert("When sin(\u2220) = " + sin + " :" + "\n\n" + "sin\u2212\u00B2(A) = " + sin1d + "\u00B0");
return;
}
if (!document.inverse.inverse-cb1.checked && !document.inverse.inverse-cb3.checked){ //no sine and tangent input
window.alert("When cos(\u2220) = " + cos + " :" + "\n\n" + "cos\u2212\u00B2(A) = " + cos1d + "\u00B0");
return;
}
if (!document.inverse.inverse-cb1.checked && !document.inverse.inverse-cb2.checked && !document.inverse.inverse-cb3.checked){ //no input or checked boxes
window.alert("Please input a number or check the correct boxes.");
return;
}
else {
window.alert("When sin(\u2220) = " + sin + ", cos(\u2220) = " + cos + ", and tan(\u2220) = " + tan + " :" + "\n\n" + "sin\u2212\u00B2(A) = " + sin1d + "\u00B0" + "\n" + "cos\u2212\u00B2(A) = " + cos1d + "\u00B0" + "\n" + "tan\u2212\u00B2(A) = " + tan1d + "\u00B0");
return;
}
}
The Question: The multiple if statements are not working so the function never returns. How can it be made to check to conditions of the input and respond in the proper way?
I can't tell you what to do to make it "work", since your desired result is pretty unclear, but a number of problems in your code jumped out at me as I skimmed it top to bottom. Some will still run but give results you aren't expecting, but at least one problem will cause an error and stop the function running. So:
Most of your comments are either redundant and could be removed, or could be made redundant and removed if you made your variable names more descriptive.
The statement
if (isNaN(document.inverse.sin.value) == true || ...)
could be made simpler because you've already declared a variable sin that is equal to document.inverse.sin.value and the == true part is redundant. Just say
if (isNan(sin) || isNan(cos) || isNan(tan)) {
All of your "reset" statements like var sin = null; are both wrong and pointless because (a) using var means you are attempting to redeclare the variables (I think JS just ignores this), so you should just say sin = null;, but in any case (b) they're local variables within your trigI() function so they're all about to disappear anyway when the function returns. If you are trying to clear the fields on the screen you need to say document.inverse.sin.value = "";, but you don't want to annoy the user by clearing all the fields just because one of them was invalid. Tell them which field had a problem, set focus to that field, and let them correct it themselves.
Most of your if statement test something like this:
if (document.inverse-cb1.checked == 'false'){
Which will never be true because you are comparing the .checked property that is a boolean equal to true or false with the string 'false'. You need to say
if (document.inverse-cb1.checked == false){ // note: no quotes
// OR, even better
if (!document.inverse-cb1.checked){
What is sup.sup() supposed to do? sup is a variable that you've set to -1. sup() is a non-existent function that in any case you shouldn't be trying to call as a method of a number. Fix this first, because I think this is what is stopping the function returning.
EDIT: I noticed another big problem:
document.inverse.inverse-cb1.checked
You can't use the "dot" object notation for properties that don't follow the rules for JS identifier naming, and JS identifiers can't have a "-" in them. So although "inverse-cb1" is a valid property name you have to use the array-style bracket [] syntax to access it:
document.inverse["inverse-cb1"].checked
Or you could just remove the "-" from both the html and your JS.