Distance Calculator HTML - javascript

Good Day ! Help is greatly appreciated !
function ShowDistance() {
var x1 = parsefloat(document.getElementById('xOne').value);
var x2 = parsefloat(document.getElementById('xTwo').value);
var y1 = parsefloat(document.getElementById('yOne').value);
var y2 = parsefloat(document.getElementById('yTwo').value);
var distance = Math.sqrt(Math.pow((x1 - x2), 2) + Math.pow((y1 - y2), 2));
return distance;
if (!isNaN(result)) {
document.getElementById('outPut').innerHTML = 'The distance bewtween (' + x1 + ',' + y1 + ') and (' + x2 + ',' + y2 + ') is ' + distance + ;
}
}
<!doctype html>
<html>
<head>
<title> Distance Calculator </title>
</head>
<body>
<h2>Distance Calculator</h2>
Coordinate 1 (<input type="text" id="xOne" size=12 value=''> ,
<input type="text" id="yOne" size=12 value=''>)
<br> Coordinate 2 (<input type="text" id="xTwo" size=12 value=''> ,
<input type="text" id="yTwo" size=12 value=''>)
<br>
<br>
<button onclick="ShowDistance()">Calculate</button>
</body>
</html>
can't print the result. That is the only problem . I can't print the result.
Please help me. your reply will be great much appreciated

There are a lot of mistakes in your code;
1- First of all, not parsefloat it should be parseFloat;
2- The second one, you return from the ShowDistance without showing the result;
3- Third one, in the if clause should be if(!isNaN(distance)) and not if(!isNaN(result));
4- You did forget to create the Html tag with output id where you wanted to print the result.
all of the code;
<!doctype html>
<html>
<head>
<title> Distance Calculator </title>
</head>
<body>
<h2>Distance Calculator</h2>
Coordinate 1 (<input type="text" id="xOne" size=12 value=''> ,
<input type="text" id="yOne" size=12 value=''>)
<br>
Coordinate 2 (<input type="text" id="xTwo" size=12 value=''> ,
<input type="text" id="yTwo" size=12 value=''>)
<br>
<br>
<button onclick="ShowDistance()">Calculate</button>
<div id="outPut">
</div>
<script>
function ShowDistance()
{
var x1=parseFloat(document.getElementById('xOne').value);
var x2=parseFloat(document.getElementById('xTwo').value);
var y1=parseFloat(document.getElementById('yOne').value);
var y2=parseFloat(document.getElementById('yTwo').value);
var distance =Math.sqrt( Math.pow((x1-x2), 2) + Math.pow((y1-y2), 2) );
if (!isNaN(distance))
{
document.getElementById('outPut').innerHTML='The distance bewtween (' + x1 + ',' + y1 + ') and (' + x2 + ',' + y2 + ') is '+ distance;
}
return distance;
}
</script>
</body>
</html>

return distance;
Will cause any subsequent code not to be ran, as the return keyword will stop the execution of code, so:
if (!isNaN(distance))
{
document.getElementById('outPut').innerHTML='The distance bewtween (' + x1 + ',' + y1 + ') and (' + x2 + ',' + y2 + ') is '+ distance;
}
Will never run.
Place the code above the return, or remove the return as the value it returns isn't used. You should see a new result.

Related

JavaScript: Combining functions and scripts and buttons

I am going through the SAMS Learn JavaScript in 24 hours book. The end of lesson three has an extra exercise to combine a Celsius to Fahrenheit from Lesson 2, with functions and buttons from Lesson 3. I was able to successfully complete the Try It exercises in Lessons 2 and 3...
LESSON 2
<!DOCTYPE html>
<html>
<head>
<title>Fahrenheit From Celsius</title>
</head>
<body>
<script>
var cTemp = 100; // temperature in Celsius
var hTemp = ((cTemp * 9) /5 ) + 32;
document.write("Temperature in Celsius: " + cTemp + " degrees<br/>");
document.write("Temperature in Fahrenheit: " + hTemp + " degrees");
</script>
LESSON 3
<!DOCTYPE html>
<html>
<head>
<title>Calling Functions</title>
<script>
function buttonReport(buttonId, buttonName, buttonValue) {
var userMessage1 = "Button id: " + buttonId + "\n";
var userMessage2 = "Button name: " + buttonName + "\n";
var userMessage3 = "Button value: " + buttonValue;
alert(userMessage1 + userMessage2 + userMessage3);
}
</script>
But I am stuck combining the two.
EXERCISE TO COMBINE THE TWO:
Write a function to take a temperature value in Celsius as an argument and return the equivalent temperature in Fahrenheit, basing it on the code from Lesson 2.
Test your function in an HTML page having three buttons that, when clicked, pass values of 10, 20, and 30 degrees Celsius, respectively, to the function.
HERE'S WHAT I HAVE...(minus the headers, titles and HTML tags)
function temp(10, 20, 30) {
var hTemp1 = ((temp * 9) /5 ) + 32;
var hTemp2 = ((temp * 9) /5 ) + 32;
var hTemp3 = ((temp * 9) /5 ) + 32;
alert(hTemp1, hTemp2, hTemp3);
}
</script>
</head>
<body>
<input type="button" value="10 X Celsius" onclick = hTemp1>
<input type="button" value="20 X Celsius" onclick = hTemp2>
<input type="button" value="30 X Celsius" onclick = hTemp3>
Can you please help me?
There's definitely better ways to do this. But here's a solution for the purpose of this lesson. I tried not to change too much of your code. Check out the snippet below.
function toF(cTmp) {
return cTmp * 9 / 5 + 32
}
function alertF(tmp) {
alert(toF(tmp))
}
<input type="button" value="10" onclick="alertF(10)">
<input type="button" value="20" onclick="alertF(20)">
<input type="button" value="30" onclick="alertF(30)">

I wrote a JavaScript to move a cat on canvas: "ฅ(*ΦωΦ*) ฅ" But the cat jumps weirdly

I created a script that uses HTML input buttons to move a cat on canvas. Each click moves the cat by 10 pixels in the direction that is clicked (moveUp(); moveDown();moveLeft(); moveRight();). This script works fine for the first 10-20 clicks, but then the cat eventually jumps around or is stuck in one spot.
I have no idea why it behaves in this way. can anyone help?
The program is on jsfiddle, you can test it out
https://jsfiddle.net/rockmanxdi/h2sk2sjz/2/
JavaScript code is hereunder:
let surface=document.getElementById("drawingArea");
let ctx=surface.getContext("2d");
let cor_x;
let cor_y;
/** draw a cat
* input the coordinates x and y for the center of the cat
* does not return, output the drawing only.
*/
let drawCat = function (x, y) {
ctx.save();
ctx.translate(x, y);
ctx.fillText("ฅ(*ΦωΦ*) ฅ", -20,-5);
ctx.restore();
};
let updateCoordinate = function(x_increment,y_increment){
console.log("before:" + cor_x + "/" + cor_y);
cor_x += 10 * x_increment;
cor_y += 10 * y_increment;
console.log("updated:" + cor_x + "/" + cor_y);
};
let moveUp = function (){
updateCoordinate(0,-1);
console.log(cor_x + "/" + cor_y );
ctx.clearRect(0,0,surface.width,surface.height);
drawCat(cor_x,cor_y);
};
let moveLeft = function (){
updateCoordinate(-1,0);
console.log( cor_x + "/" + cor_y );
ctx.clearRect(0,0,surface.width,surface.height);
drawCat(cor_x,cor_y);
};
let moveRight = function (){
updateCoordinate(1,0);
console.log( cor_x + "/" + cor_y );
ctx.clearRect(0,0,surface.width,surface.height);
drawCat(cor_x,cor_y);
};
let moveDown = function (){
updateCoordinate(0,1);
console.log(cor_x + "/" + cor_y );
ctx.clearRect(0,0,surface.width,surface.height);
drawCat(cor_x,cor_y);
};
let reset = function(){
cor_x=surface.width/2.0;
cor_y=surface.height/2.0;
console.log(cor_x + "/" + cor_y );
ctx.clearRect(0,0,surface.width,surface.height);
drawCat(cor_x,cor_y);
}
drawCat(200,200);
html body:
<canvas width="400" height="400" id="drawingArea" style="border:solid">cat image</canvas>
<p>
<input type="button" id="resetBtn" value="reset" onclick="reset();" />
</p>
<p>
<input type="button" id="upBtn" value="Up" onclick="moveUp();"/>
</p>
<p>
<input type="button" id="leftBtn" value="Left" onclick="moveLeft();"/>
<input type="button" id="rightBtn" value="Right" onclick="moveRight();"/>
</p>
<p>
<input type="button" id="downBtn" value="Down" onclick="moveDown();"/>
</p>
By the way, I put console.log() inside updateCoordinate(); and move UP/Down/Right/Left(); functions to track the value of the x and y coordinates of the cat. Press F12 to track the value.
1) I replaced only all let to var (everything is working good):
var surface=document.getElementById("drawingArea");
var ctx=surface.getContext("2d");
var cor_x;
var cor_y;
/** draw a cat
* input the coordinates x and y for the center of the cat
* does not return, output the drawing only.
*/
var drawCat = function (x, y) {
ctx.save();
ctx.translate(x, y);
ctx.fillText("ฅ(*ΦωΦ*) ฅ", -20,-5);
ctx.restore();
};
var updateCoordinate = function(x_increment,y_increment){
console.log("before:" + cor_x + "/" + cor_y);
cor_x += 10 * x_increment;
cor_y += 10 * y_increment;
console.log("updated:" + cor_x + "/" + cor_y);
};
var moveUp = function (){
updateCoordinate(0,-1);
console.log(cor_x + "/" + cor_y );
ctx.clearRect(0,0,surface.width,surface.height);
drawCat(cor_x,cor_y);
};
var moveLeft = function (){
updateCoordinate(-1,0);
console.log( cor_x + "/" + cor_y );
ctx.clearRect(0,0,surface.width,surface.height);
drawCat(cor_x,cor_y);
};
var moveRight = function (){
updateCoordinate(1,0);
console.log( cor_x + "/" + cor_y );
ctx.clearRect(0,0,surface.width,surface.height);
drawCat(cor_x,cor_y);
};
var moveDown = function (){
updateCoordinate(0,1);
console.log(cor_x + "/" + cor_y );
ctx.clearRect(0,0,surface.width,surface.height);
drawCat(cor_x,cor_y);
};
var reset = function(){
cor_x=surface.width/2.0;
cor_y=surface.height/2.0;
console.log(cor_x + "/" + cor_y );
ctx.clearRect(0,0,surface.width,surface.height);
drawCat(cor_x,cor_y);
}
drawCat(200,200);
<body onload="reset();">
<main>
<!-- place your HTML code within the main -->
<canvas width="400" height="400" id="drawingArea" style="border:solid">cat image</canvas>
<p>
<input type="button" id="resetBtn" value="reset" onclick="reset();" />
</p>
<p>
<input type="button" id="upBtn" value="Up" onclick="moveUp();"/>
</p>
<p>
<input type="button" id="leftBtn" value="Left" onclick="moveLeft();"/>
<input type="button" id="rightBtn" value="Right" onclick="moveRight();"/>
</p>
<p>
<input type="button" id="downBtn" value="Down" onclick="moveDown();"/>
</p>
</main>
</body>
It is bug with let variable:
From console log:
(index):96 before:160/390
(index):99 updated:160/400
(index):126 160/280
Within updateCoordinate: cor_x = 160; cor_y = 400 BUT within moveRight (or moveLeft, moveUp, moveDown) cor_x = 160; cor_y = 280

What's wrong with my HTML and javascript code?

I want to implement a simple measurement convergence program but the convert button doesn't really work and it's not even changing the value of the answer box. What should I do now?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Measurement Conversion</title>
</head>
<body>
<h1 align="center">
Measurement Conversion
</h1>
<div align="center"><center><table border="0">
<tr>
<input type="text" name="what" size="15">
</tr>
<tr>
<td align="center">From:<br>
<select name="unit" size="9" onChange="convert()">
<option name="meter">meter</option>
<option name="mile">mile</option>
<option name="yard">yard</option>
</select></td>
</tr>
<tr>
<input type="button" onclick="convert()">Convert it now!</button></td>
</tr>
<tr>
<input type="text" name="answer" title="answer" size="70" value="None"></td>
</tr>
</table>
</center></div>
<script>
function convert() {
// var FromVal, ToVal, FromName, ToName, v1;
v1 = document.getElementByName("what").value;
document.getElementByName("answer").value = v1;
var unit = document.getElementByName("unit").name;
if (unit == "yard") {
var meter = "meter= " + 0.9144*document.getElementByName("what").value;
var mile = "mile = " + 0.000568181818*document.getElementByName("what").value;
document.getElementById("answer").value = meter + mile;
}
if (unit == "meter") {
var yard = "yard = " + 1.0936133*document.getElementByName("what").value;
var mile = "mile = " + 0.000621371192*document.getElementByName("what").value;
// var meter = "m = " + 0.9144*document.getElementByName("what").value
document.getElementById("answer").value = yard + mile;
}
if (unit == "mile") {
var meter = "meter = " + 1609.344*document.getElementByName("what").value
var yard = "yard = " + 1760*document.getElementByName("what").value
document.getElementById("answer").value = meter + yard;
}
}
</script>
</body>
</html>
It seems there is something wrong with my convert() function.
How about using the most basic troubleshooting methods first and then coming here and asking specific questions to help get you through the problem.
Add an alert("button Clicked");
to the first line of your function and see if you get the alert. If you do, move the alert to after your variable statements and change it to
alert("what = " + what + ", "answer = " + answer + ", unit = " + unit);
and make sure you are getting what you expect for your variable assignments. Continue like this and when you get to a specific problem that your can't seem to remedy yourself, come back.
there's no getElementByName.
add attribute id on your input then use getElementById instead.

Simple Javascript Calculator

I'm trying to learn Javascript and I feel like I have a decent grasp on the fundamentals but I am having problems making it do things that i want .. for example.. I am trying to create a simple form in html that calculates the sum of 2 numbers.. here is my html and javascript:
<head>
<script type="text/javascript">
function adder(a,b) {
var a = document.getElementById('firstNum').value;
var b = document.getElementById('secondNum').value;
var numbers = new Array(a,b);
var sum = 0;
for (i=0; i < numbers.length; i++) {
sum += parseInt(numbers[i]);
}
//this part i need help with
document.getElementById('answer').write("First Number: " + a + " plus Second Number: " + b + " is " + sum).value; //this part i need help with
</script>
</head>
<body>
<form id="additionForm">
A + B = C : <input type="text" id="firstNum" placeholder="A">
+ <input type="text" id="secondNum" placeholder="B">
<input type="button" id="addBtn" value="Add" onClick="adder();">
= <input type="text" id="answer" placeholder="C">
</form>
</body>
My problem is that i don't know how to get the javascript to overwrite the value attribute for my form input id=answer .. or if i'm supposed to be using Jquery instead .. thanks in advance.
function adder() {
var a = parseInt( document.getElementById('firstNum').value, 10);
var b = parseInt( document.getElementById('secondNum').value, 10);
var sum = a + b;
//this part i need help with
document.getElementById('answer').value = "First Number: " + a + " plus Second Number: " + b + " is " + sum).value; //this part i need help with
}
If you want to modify an input field in javascript, you can simply set the value attribute:
document.getElementById('answer').value = "First Number: " + a + " plus Second Number: " + b + " is " + sum;

Jquery Nested Functions Not Working

The purpose of my code is to solve a system of three equations.
What I want to happen is for the "p" selector and the "answer" class to be hidden. When there is a "click" event on an "h1" selector, I want it to show the next element. However, after there is a click event on the class "button" I want the "matrix" class to slide up and then the "answer" class to slide down, revealing the answer to the HTML form's results while hiding or "slideUp"ing the original form and heading.
Originally the "my_code.js" file had no problem hiding the "p" element and slideToggling it when an h1 selector before it was clicked, but once I added the additional code, things went south.
What is happening in my jquery script? Am I targeting ancestors elements incorrectly?
JQUERY DOCUMENT
$(document).ready(function() {
$("p, .answer").hide();
$("h1").click(function() {
$(this).next().slideToggle(300);
});
$(".button")click(function() { //after form submission
$(".matrix").slideUp(300, function(){ //hiding the matrix form
$(".answer").slideDown(300); //and display the answer
});
});
});
HTML DOCUMENT
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="stylesheet.css" />
<title>Kremer's Rule: System of Three Equations</title>
<script language="JavaScript">
function testResults (form) {
function system (x1, x2, x3, y1, y2, y3, z1, z2, z3, a1, a2, a3){
this.x1 = x1;
this.x2 = x2;
this.x3 = x3;
this.y1 = y1;
this.y2 = y2;
this.y3 = y3;
this.z1 = z1;
this.z2 = z2;
this.z3 = z3;
this.a1 = a1;
this.a2 = a2;
this.a3 = a3;
this.calcDanswer = function() {
return (this.x1*((this.y2*this.z3)-(this.z2*this.y3))) - (this.y1*((this.x2*this.z3)-(this.z2*this.x3))) + (this.z1*((this.x2*D.y3)- (this.y2*this.x3)));
};
this.calcXanswer = function(){
return (this.a1*((this.y2*this.z3)-(this.z2*this.y3))) - (this.y1*((this.a2*this.z3)-(this.z2*this.a3))) + (this.z1*((this.a2*this.y3)-(this.y2*this.a3)));
};
this.calcYanswer = function(){
return (this.x1*((this.a2*this.z3)-(this.z2*this.a3))) - (this.a1*((this.x2*this.z3)-(this.z2*this.x3))) + (this.z1*((this.x2*this.a3)-(this.a2*this.x3)));
};
this.calcZanswer = function(){
return (this.x1*((this.y2*this.a3)-(this.a2*this.y3))) - (this.y1*((this.x2*this.a3)-(this.a2*this.x3))) + (this.a1*((this.x2*this.y3)-(this.y2*this.x3)));
};
}
var x1 = form.x1.value;
var x2 = form.x2.value;
var x3 = form.x3.value;
var y1 = form.y1.value;
var y2 = form.y2.value;
var y3 = form.y3.value;
var z1 = form.z1.value;
var z2 = form.z2.value;
var z3 = form.z3.value;
var a1 = form.a1.value;
var a2 = form.a2.value;
var a3 = form.a3.value;
var D = new system(x1, x2, x3, y1, y2, y3, z1, z2, z3, a1, a2, a3);
var X = D.calcXanswer()/D.calcDanswer();
var Y = D.calcYanswer()/D.calcDanswer();
var Z = D.calcZanswer()/D.calcDanswer();
// printing to console
var out = document.getElementById('real-answer');
out.innerHTML += "<b>The equations are:</b>" + "<br />" +
D.x1 + "x + " + D.y1 + "y + " + D.z1 +"z = "+D.a1 + "<br />" +
D.x2 + "x + " + D.y2 + "y + " + D.z2 +"z = "+D.a2 + "<br />" +
D.x3 + "x + " + D.y3 + "y + " + D.z3 +"z = "+D.a3 + "<br /><br />" +
"The answer for D is " + D.calcDanswer() + "<br />" +
"The answer for Dx is " + D.calcXanswer() + "<br />" +
"The answer for Dy is " + D.calcYanswer() + "<br />" +
"The answer for Dy is " + D.calcZanswer() + "<br />" +
"X is " + X + "<br />" +
"Y is " + Y + "<br />" +
"Z is " + Z;
}
</SCRIPT>
</head>
<body>
<!--DIRECTIONS-->
<h1><span id="highlight">How Does This Work?</span></h1>
<p>Type in all the information for your system of three equations.<br />
When finished hit "Go".</p>
<!--Form-->
<p class="matrix">
<FORM NAME="myform" ACTION="" METHOD="GET">
<input type="text" name="x1"> x + <input type="text" name="y1"> y + <input type="text" name="z1"> z = <input type="text" name="a1"><br />
<input type="text" name="x2"> x + <input type="text" name="y2"> y + <input type="text" name="z2"> z = <input type="text" name="a2"><br />
<input type="text" name="x3"> x + <input type="text" name="y3"> y + <input type="text" name="z3"> z = <input type="text" name="a3"><br />
<input type="button" class="button" name="button" value="GO" onClick="testResults(this.form)">
</form>
</p>
<div id="answer">
<h1><span id="highlight">The Answer:</span></h2>
<div id='real-answer'></div>
</div>
</body>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
<script type="text/javascript" src="my_code.js"></script>
</html>
Your Jquery code line #9:
$(".button")click(function() {
You are missing a "." after the selector:
$(".button").click(function() {
I see a number of issues:
You missed a period in $(".button")click, should be $(".button").click
The fiddle had a closing script tag (which aren't needed there, fyi) but you had no closing brackets for the document.ready function
You have an inline onClick handler calling a function defined inside the document.ready function. That won't be visible to the html element. You're using jquery already so just use a click handler
You have several functions wrapped inside each other for the calculator part, that's not needed and will cause some scope problems. You're mixing native js with jquery as well, document.getElement* type code when you have the $ selector available
A fiddle to get you started
Your second <h1> (the new one) is closed with </h2>. (Might not be the primary problem.)

Categories