Jump to content

Noob to javascript.


ace799

Recommended Posts

Taking a free course i found online. The 2nd assignment that I am stuck on. Create a Web page that asks users for a value. The program should then display the square(num * num) and the cube (num*num*num) of the number on the screen.

Can anyone give me some help to get me started?

 

So far I have this written out but I have no clue how to take the inputted value and calculate using a variable...? Any help would be much appreciated!!

 

<html>

<head>
<title>Logical AND Operator</title>
</head>
<body bgcolor="lightblue">
<big>
<script type="text/javascript">
var answer = prompt("Enter a value", "");
</script>
</big>
</body>
</html>
Link to comment
Share on other sites

<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><title>Boilerplate Code</title><style>body{background-color: lightblue;}</style><script>window.onerror = function(m, u, l){alert('Javascript Error: '+m+'nURL: '+u+'nLine Number: '+l);return true;}</script><script>window.onload = init;function init(){document.getElementById('btn').onclick = calc;}function calc(){var i = document.getElementById('in1').value;document.getElementById('out1').innerHTML = 'i='+ i +'<br/>i*i='+ i*i +'<br/>i*i*i='+ i*i*i;}</script></head><body><p>Calculate the square and cube of a number</p><input type="text" id="in1"/><input type="button" id="btn" value="Enter"/><div id="out1"></div></body></html>
Edited by davej
Link to comment
Share on other sites

<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><title>three popups</title><style>body{background-color:lightblue;}</style><script>window.onload = init;function init(){document.getElementById('btn').onclick = run;}function run(){var response1 = prompt("Enter a value", "");var response2 = confirm("Did you enter "+ response1 +" ?");if(response2==true){var answer = response1*response1;alert("The value "+ response1 +" squared is: "+ answer); }else{alert("Calculation cancelled");}}</script></head><body><input type="button" id="btn" value="Begin"/></body></html>

I really have to wonder about the quality of this free online Javascript course you are taking. You might be better off looking for a different online tutorial. There are many of them and many include obsolete or semi-obsolete material. W3schools has one. You might also look at... https://developer.mozilla.org/en-US/docs/Web/JavaScript

Edited by davej
Link to comment
Share on other sites

its been so long since I've seen a <big> tag that I didn't recognize it. its highly likely that the tutorial you are using is either out-of-date or might pass off "bad coding" practices.

 

---

A single '=' is an assignment operator. what the code does is it evaluates everything to the right of the '=' operator and stores the result of that evaluation into a variable or property thats on the left of the '=' operator. so if you see some code say:

var x = 1+2;

javascript will "add" 1 and 2 together, since a '+' between the two numbers implies that you want to perform addition on them. the '=' operator will then take the result of that evaluation (which is 3, since 1+2 is 3) and store that in the variable x. so when x is used, the browser will see x as 3.

---

anywho, "var answer" is storing the value that the user gives the browser, and the browser is storing that in its memory. now all you need to do is create another variable that will store the math that you do to "answer". there are numerous ways you can accomplish this, as shown here:

// directly calculate the result in one linevar result2 = answer * answer; //OR first define the result and then recall the result,// multiply in the answer, and reassign the new resultvar result2 = 1;result2 = result2 * answer;result2 = result2 * answer;//OR use a for loop and the *= operator to constantly // update and reassign the resultvar result2 = 1;for(var i=1;i<=2:i++){  result2 *= answer;}//OR use a pre-defined function to do the work for youvar result2 = Math.pow(answer,2);

Of course, there are many more ways you can calculate the result. I prefer the use of pre-defined functions when possible as it can save you time from "re-inventing the wheel". all the logic is already there. There may be times where using predefined functions can have different effects based on the browser, but that's out of the scope of this lesson.

 

Now that you've figured out the result of the answer squared (which you have stored in the variable "result2"), it now comes time for you to add code so that the browser shows you the result. Right now the browser knows the result and has it memorized, but you haven't told the browser to tell you what that result is. Again, there's multiple ways the browser can tell you this result. be it through the console, alert, or by directly modifying the HTML on the page. The simplest way by far, code-wise, is to just use alert:

alert(result2);

In most cases you do NOT want to use alert in your code, alert is highly disruptive to a webpage (everything must stop and wait for the user to hit ok). You will usually want to manipulate the HTML, or use console if you need to debug a problem. However, alert works great in times when you're trying to learn how to code, like in tutorials. Now lets piece together what we know so far:

<script type="text/javascript">  var answer = prompt("Enter a value", "");  var result2 = Math.pow(answer,2);  alert(result2); </script>

now that I've shown you how to do squared, see if you can do the cubed.

Link to comment
Share on other sites

ty so much! Your of great help to me.

 

This is what I came up with.

 

 

<script type="text/javascript">
var answer = prompt("Enter a value", "");
var result2 = Math.pow(answer,2);
alert(result2);
var result2 = Math.pow(answer,3);
alert(result2);
</script>
How would I build a non alert one with a built in input value box for the user. And then display it on the page. So basically no alert boxes at all.
Link to comment
Share on other sites

To do that you need to start diving into DOM manipulation and learning how to assign events. The sample code below is a quick example of how almost everyone learned how to do both of those (usually both around the same time)

<!DOCTYPE html><html>  <head>    <script>      function calc(){        var base = document.getElementById("base").value;        var exp  = document.getElementById("exponent").value;        var output = document.getElementById("output");        output.innerHTML = Math.pow(base,exp);      }    </script>  </head>  <body>    <input type="text" id="base" onkeyup="calc()" value="5">^    <input type="text" id="exponent" onkeyup="calc()" value="2">    <p>output:      <span id="output">25</span>    </p>  </body></html>

When you start playing with the "document" (and stuff it gives you) is when you start messing with DOM manipulation. The most common method that everyone uses is document.getElementById() and the most common properties accessed are className, innerHTML, and value. Of course the DOM is a lot bigger than just these few properties/methods. I would recommend studying the DOM when you can (but not all in one sitting, theres alot in it and you'll likely not use most of it). w3schools has a good tutorial to introduce you to the ins and outs of the dom.

In my code sample, I assigned onkeyup events to the <input> tags. This means that every time you release a key while either of those 2 tags are selected, it will run the code I have in it's quotes. In this example that means it will run the function "calc" which was previously defined. The way I assigned the events in my sample code is via "inline assignment". The primary reason I used inline assignment is that I think its the simplest way for you to follow along.

assigning events can range from simplistic to complex. Due to lack of all browsers (mostly IE) conforming to a standard way of defining events, assigning events has become a chore. Inline assignment is the most compatible (all browsers for at least the past decade support it) and is straightforward to add, but is greatly frowned upon. The reason is because its highly inflexible and doesn't allow full separation between the HTML and javascript. For example, if you use DOM manipulation to add or remove elements you can't use inline assigment on them. Davej's earlier post is how you should assign events to elements.

 

jQuery is a framework whose whole purpose is to greatly simplify DOM manipulation and event calling across nearly every browser (at least the ones that matter). Its so concise that its even easier to code events than using inline assignment. With jQuery, you don't have to know how actual DOM manipulation or event assignment/calling works. But all the same, its recommended that you study up on them anyway.

 

I mean a mechanic is better at his job if he knows more about an engine than just "pressing the gas pedal makes it go".

  • Like 1
Link to comment
Share on other sites

Life is too short to spend on a tutorial that is still teaching the <big> tag.

 

Advice for Ace799: Look at these tutorials...

 

http://www.w3schools.com/js/

 

(W3schools has a good tutorial with the exception that it excessively uses document.write() and inline code -- so look at the examples but don't use document.write() -- instead come here to the forum and ask us how it should be done, and also don't always use inline Javascript and inline CSS -- instead come here to the forum and ask how it can alternately be done.)

 

Also...

 

http://www.codecademy.com/tracks/javascript

Edited by davej
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...