What am I missing in my JavaScript code? - javascript

I'm new to JavaScript and I’m having issues trying to create a drop down list unit converter. The project calls for the code to convert miles to feet, Celsius to Fahrenheit and pounds to grams. The issue is when I enter the values the output is way off.
No matter what number I enter or unit I select I get the same result of 14514.944, instead of the appropriate (5280 feet, 33.8°, 453.592g, etc.). If I double click the submit button I get 62573043513.9154, triple click 269748534086686000, etc.
I know I’m missing something in the convert_unit function, but I’m not sure what. I’ve tried adding and removing various code and nothing is working.
var numInput = document.getElementById("numInput");
var numInput = document.getElementById("numOutput");
var feet = document.getElementById("feet");
var fahrenheit = document.getElementById("fahrenheit");
var grams = document.getElementById("grams");
function convert_unit() {
numOutput.value=(5280*numInput.value);
var x = document.getElementById("feet").label;
document.getElementById("enter").innerHTML = x;
document.getElementById("results").innerHTML = x;
numOutput.value=(1.8*numInput.value)+32
var x = document.getElementById("fahrenheit").label;
document.getElementById("enter").innerHTML = x;
document.getElementById("results").innerHTML = x;
numOutput.value=(453.592*numInput.value)
var x = document.getElementById("grams").label;
document.getElementById("enter").innerHTML = x;
document.getElementById("results").innerHTML = x;
}
<form>
<fieldset>
<label id="enter">Numeric Value</label>
<p>
<input type="number" placeholder="Enter Value" name=" " value=" " id="numInput" />
</p>
</fieldset>
<fieldset><label>Conversion Menu</label>
<p>
<select id="" name="" size="3">
<option id="feet" name="Miles to Feet">Miles to Feet</option>
<option id="fahrenheit" name="Celcius to Fahrenheit">Celcius to Fahrenheit</option>
<option id="grams" name="Pounds to Grams">Pounds to Grams</option>
</select>
</p>
</fieldset>
<fieldset>
<button type="button" id="mybutton" value=" " onClick="convert_unit()";>Convert</button>
</fieldset>
<fieldset><label id="results">Results</label>
<p>
<input type="number" placeholder="Results" name="to_unit" id="numOutput" readonly /></p>
</fieldset>
</form>

Both of your variables are named numInput:
var numInput = document.getElementById("numInput");
var numInput = document.getElementById("numOutput");
I'm guessing your second one should be numOutput. Also, there's no need to redefine these variables in JS unless you want to make it explicitly known what they are. HTML elements with IDs are already available in the global scope based on their ID name (with some caveats). In this case you could simply use numInput and numOutput throughout your program and it would still work even without these two lines.

i found 2 problems in your code.
The first is that in line 4 of the script, you overwrite the input of variable "numInput" with "numOutput" element. (Rename to 'numOutput')
The second problem is that, when script is loaded on page, the elements is not yet instanced. To solve that you can put the import tag right before </body> or add variables definition inside the function.
PS: Don't forget to use semicolons after every statement;
Jah Bless =)
index.html
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title></title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<form>
<fieldset>
<label id="enter">Pounds to Grams</label>
<p><input placeholder="Enter Value" name=" " value=" " id="numInput" type="number"></p>
</fieldset>
<fieldset>
<label>Conversion Menu</label>
<p>
<select id="" name="" size="3">
<option id="feet" name="Miles to Feet">Miles to Feet</option>
<option id="fahrenheit" name="Celcius to Fahrenheit">Celcius to Fahrenheit</option>
<option id="grams" name="Pounds to Grams">Pounds to Grams</option>
</select>
</p>
</fieldset>
<fieldset>
<button type="button" id="mybutton" value=" " onclick="convert_unit()" ;="">Convert</button>
</fieldset>
<fieldset>
<label id="results">Pounds to Grams</label>
<p><input placeholder="Results" name="to_unit" id="numOutput" readonly="" type="number"></p>
</fieldset>
</form>
<script src="script.js"></script>
</body>
</html>
script.js
function convert_unit() {
var numInput = document.getElementById('numInput');
var numOutput = document.getElementById('numOutput');
var feet = document.getElementById("feet");
var fahrenheit = document.getElementById("fahrenheit");
var grams = document.getElementById("grams");
numOutput.value=(5280*numInput.value);
var x = document.getElementById("feet").label;
document.getElementById("enter").innerHTML = x;
document.getElementById("results").innerHTML = x;
numOutput.value=(1.8*numInput.value)+32;
var x = document.getElementById("fahrenheit").label;
document.getElementById("enter").innerHTML = x;
document.getElementById("results").innerHTML = x;
numOutput.value=(453.592*numInput.value);
var x = document.getElementById("grams").label;
document.getElementById("enter").innerHTML = x;
document.getElementById("results").innerHTML = x;
}

Your code corrected, customized and working perfectly!
var numInput = document.getElementById("numInput");
var numOutput = document.getElementById("numOutput");
var feet = document.getElementById("feet");
var fahrenheit = document.getElementById("fahrenheit");
var grams = document.getElementById("grams");
function convert_unit() {
if(numInput.value === "") {
if(confirm("No value inputed to convert! Consider default 1 unit?")) {
numInput.value = 1;
}
}
if(getSelectedUnitToConvert("conversion_type") == null) {
if(confirm("No conversion unit selected! Consider default Miles to Feet?")) {
document.getElementById("conversion_type").selectedIndex = 0;
}
}
if(getSelectedUnitToConvert("conversion_type") == "Miles to Feet") {
numOutput.value=numInput.value;
numOutput2.value=(5280*numInput.value);
var x = document.getElementById("feet").label;
document.getElementById("result1").innerHTML = "Miles";
document.getElementById("result2").innerHTML = "Feet";
} else if(getSelectedUnitToConvert("conversion_type") == "Celcius to Fahrenheit") {
numOutput.value=numInput.value;
numOutput2.value=(1.8*numInput.value)+32;
var x = document.getElementById("fahrenheit").label;
document.getElementById("result1").innerHTML = "Celcius";
document.getElementById("result2").innerHTML = "Fahrenheit";
} else if(getSelectedUnitToConvert("conversion_type") == "Pounds to Grams") {
numOutput.value=numInput.value;
numOutput2.value=(453.592*numInput.value);
var x = document.getElementById("grams").label;
document.getElementById("result1").innerHTML = "Pounds";
document.getElementById("result2").innerHTML = "Grams";
}
}
function getSelectedUnitToConvert(elementId) {
var elt = document.getElementById(elementId);
if (elt.selectedIndex == -1) {
return null;
}
return elt.options[elt.selectedIndex].text;
}
div {
margin: 5px;
}
<form>
<fieldset>
<label id="enter">Value to Convert</label>
<p><input type="number" placeholder="Enter Value" value="" id="numInput" /></p>
</fieldset>
<fieldset><label>Units for Conversion</label>
<p><select id="conversion_type" size="3">
<option id="feet" name="Miles to Feet">Miles to Feet</option>
<option id="fahrenheit" name="Celcius to Fahrenheit">Celcius to Fahrenheit</option>
<option id="grams" name="Pounds to Grams">Pounds to Grams</option>
</select></p>
</fieldset>
<fieldset>
<button type="button" id="mybutton" value="" onclick="convert_unit();">Convert</button>
</fieldset>
<fieldset><label id="results">Conversion Result:</label>
<p>
<div>
<input placeholder="Original Value" name="to_unit" id="numOutput" readonly />
<label id="result1"></label>
</div>
<div>
<input placeholder="Conversion Result" name="to_unit2" id="numOutput2" readonly />
<label id="result2"></label>
</div>
</p>
</fieldset>
</form>

Related

I cannot get the javaScript to do the function i am requesting it to do, in my case multiply two values by a hidden and then add a final value

I am so lost as to why this is not working properly, as it is on similar previous code. This is for field personnel, a cheat Sheet to simply enter values and get a fast answer (calculation). They enter the value of Num5/6/7 code multiplies 3 values one hidden then adds the last value together and upon click button the result is shown.
Here is my code (taken from copy/paste of a working conversion).
<div class="containerHydro">
<p>
<label >Fluid Column Length</label>
<input type="number" id="num5">
<label >Fluid Weight</label>
<input type="number" id="num6">
<label >Well Head Pressure</label>
<input type="number" id="num7">
<p>
<input type="button" value="Sum" onclick="calculate()"/>
</p>
<p id="total1"></p>
</div>
The Function also copy/paste of multiply two int then divide by hidden (which works BTW)
function calculate() {
var numFive = document.getElementById('num5').value;
var numSix = document.getElementById('num6').value;
var numSvn = document.getElementById('num7').value;
var total1 = parseInt(numFive) * parseInt(numSix) * 0.052 + parseInt('numSvn');
var p =document.getElementById('total1');
p.innerHTML += total1;
}
Here is the same idea which works fine-
Code-
<div class="container7">
<p>
<label id="H2S Percent">H2S Percentage</label>
<input id="num3" type="number" name="num3" placeholder="H2S Percent">
<label id="H2S Percent">WHP</label>
<input id="num4" type="number" name="num4"placeholder="Well Head Pressure" > <br>
</p>
<input type="button" value="H2S Partial Pressure" onclick="math()"/>
<p id="result"></p>
</div>
Function
function math() {
var numThree = document.getElementById('num3').value;
var numFour = document.getElementById('num4').value;
var result = parseInt(numThree) * parseInt(numFour) / 1000000;
var p = document.getElementById('result');
p.innerHTML += result;
}
function calculate() {
var numFive = document.getElementById('num5').value;
var numSix = document.getElementById('num6').value;
var numSvn = document.getElementById('num7').value;
var total1 = parseInt(numFive) * parseInt(numSix) * 0.052 + parseInt(numSvn);
var p = document.getElementById('total1');
p.innerHTML += total1;
}
input {
display: block;
}
<div class="containerHydro">
<p>
<label>Fluid Column Length</label>
<input type="number" id="num5">
<label>Fluid Weight</label>
<input type="number" id="num6">
<label>Well Head Pressure</label>
<input type="number" id="num7">
<p>
<input type="button" value="Sum" onclick="calculate()" />
</p>
<p id="total1"></p>
</div>

I am having trouble with HTML Javascript inclusion

I'm trying to use the information that I obtain through a form via a submit button, do a little processing, and print it out onto the web page, preventing it from being submitted to a web server by including (return false).
Here is the code to the page:
<html>
<head>
<title>SmithSellsStuff</title>
</head>
<body>
I'm too cheap to buy something nice
<script>
var myData = {
price: "4.25",
taxRate: "0.07",
shipRate: "0.02"
};
myData.calculateTotal = function() {
myData.name = document.getElementById("name");
myData.date = document.getElementById("date");
myData.numItems = document.getElementById("number of items");
var itemTotal = myData.numItems * myData.price;
var taxTotal = (myData.numItems * myData.price) * myData.taxRate;
var shipTotal = (myData.numItems * myData.price) * myData.shipRate;
document.writeln(itemTotal);
document.writeln(taxTotal);
document.writeln(shipTotal);
};
</script>
<form>
</p>
<label>Name: <input type="text" name="name" id="name" tabindex="1"/> </label>
</p>
<label>Delivery Date: <input type="date" name="date" id="date" tabindex="2"/></label>
</p>
<label>Number of items: <input type="number" name="number of items" id="number of items" tabindex="3"/></label>
</p>
<input type="submit" onclick="calculateTotal(); return false;"/>
</form>
</body>
</html>
On the first page, I have a simple form with a field for name, date, number of items total, and a submit button. One error I'm getting is in the onclick tag. It says '_kof_1' is defined but never used. I don't think it is allowing my calculateTotal function to call.
It's because the function was not declared in the global scope, but rather as a property of myData.
myData.calculateTotal = function() {
To solve this, simply change the call to:
<input type="submit" onclick="myData.calculateTotal(); return false;"/>
Furthermore, since you want to get the name, date, and number of items from the text fields, you have to get the .value property to get the contents of the input fields, like so:
myData.name = document.getElementById("name").value;
myData.date = document.getElementById("date").value;
myData.numItems = parseInt(document.getElementById("number of items").value);
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
I'm too cheap to buy something nice
<script>
function calculateTotal()
{
alert("hai");
var price="4.25";
var taxRate="0.07";
var shipRate="0.02";
var name = document.getElementById("name");
var date = document.getElementById("date");
var numItems = document.getElementById("number_of_items").value;
alert(numItems);
var itemTotal = numItems * price;
var taxTotal = (numItems * price) * taxRate;
var shipTotal = (numItems * price) * shipRate;
document.writeln("Total Items:"+itemTotal+"\tTax :"+taxTotal+"\tshipTotal:"+shipTotal);
}
</script>
<form>
<p>
<label>Name: <input type="text" name="name" id="name" tabindex="1"/> </label>
</p>
<label>Delivery Date: <input type="date" name="date" id="date" tabindex="2"/></label>
<p>
<label>Number of items: <input type="number" name="number_of_items" id="number_of_items" tabindex="10"/></label>
</p>
<input type="submit" onclick="calculateTotal()"/>
</form>
</body>
</html>
alert is just for to know method is calling or not, Hope this will help you

Using forms to Collect data for Javascript functions?

I'm trying to collect data via forms on one page, then transfer that data to the next page for use in a JS function.
(Specifically, I want the user to input values for A, B, and C of the Quadratic equation, and then send to a page where a script takes those values and runs the equation + outputs an answer).
Here the code for my first page --->
<body>
<h1> Welcome to the Math Equation Solver </h1>
<p> Which equation would you like to solve? (Simply input the data for the equation you wish to solve). </p>
<form name="quad" method="get" action="JS_B.html">
<input
<input type="text" name="a_val" size="5">
<br>
<input type="text" name="b_val" size="5">
<br>
<input type="text" name="c_val" size="5">
<br>
<input type="submit" method="get" action="JS_B.html" value="Submit">
<input type="hidden" name="a_val">
<input type="hidden" name="b_val">
<input type="hidden" name="c_val">
</form>
Here is the code for my second page --->
<title>JS_Math Scripts</title>
<body>
<script type="Javascript">
function answer()
{
var a = a_val
document.writeln(a_val)
var b = b_val
var c = c_val
var root = Math.pow(b, 2) - 4 * a * c
var answer1 = (-b + Math.sqrt(root)) / 2*a
var answer2 = (-b - Math.sqrt(root)) / 2*a
if(root<'0');
{
alert('This equation has no real solution.')
}else{
if(root=='0')
{
answerOne = answer1
document.writeln(answerOne)
answerTwo = 'No Second Answer'
}else{
answerOne = answer1
document.writeln(answerOne)
answerTwo = answer2
document.writeln(answerTwo)
}
}
}
// End -->
</script>
<input type="hidden" name="a_val">
<input type="hidden" name="b_val">
<input type="hidden" name="c_val">
<input type="hidden" name="answerOne">
<input type="hidden" name="answerTwo">
<input type="hidden" name="Answer">
</body>
</html>
So anyways, when I input values for A, B, and C it takes me to the second page, but I'm not getting a result. I've tried inspect element and the console isn't indicating any errors, so I think my data is transferring correctly. Any ideas?
You can use FormData() to retrieve values from <input> elements within <form>; use JSON.stringify(), encodeURIComponent() to pass values from form to JS_B.html as query string.
At window load event at JS_B.html, use decodeURIComponent(), JSON.parse() to retrieve object at location.search; destructuring assignment to set variables within answer function using passed object.
Include ; following variable assignments, remove ; following if condition
index.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1> Welcome to the Math Equation Solver </h1>
<p> Which equation would you like to solve? (Simply input the data for the equation you wish to solve). </p>
<form name="quad">
<input type="text" name="a_val" size="5">
<br>
<input type="text" name="b_val" size="5">
<br>
<input type="text" name="c_val" size="5">
<br>
<input type="submit" value="Submit">
<!--
<input type="hidden" name="a_val">
<input type="hidden" name="b_val">
<input type="hidden" name="c_val">
-->
</form>
<script>
var form = document.querySelector("form");
form.onsubmit = function(e) {
e.preventDefault();
var data = new FormData(this);
var obj = {};
for (prop of data.entries()) {
obj[prop[0]] = prop[1]
};
var query = encodeURIComponent(JSON.stringify(obj));
location.href = "JS_B.html?" + query;
}
</script>
</body>
</html>
JS_B.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
function answer(obj) {
var {
a_val: a,
b_val: b,
c_val: c
} = obj;
document.writeln(a);
var root = Math.pow(b, 2) - 4 * a * c;
var answer1 = (-b + Math.sqrt(root)) / 2 * a;
var answer2 = (-b - Math.sqrt(root)) / 2 * a;
if (root < 0) {
alert('This equation has no real solution.')
} else {
if (root == 0) {
answerOne = answer1;
document.writeln(answerOne);
answerTwo = 'No Second Answer'
} else {
answerOne = answer1;
document.writeln(answerOne);
answerTwo = answer2;
document.writeln(answerTwo)
}
}
} // End -->
window.onload = function() {
var obj = JSON.parse(decodeURIComponent(location.search.slice(1)));
console.log(obj);
answer(obj);
}
</script>
<input type="hidden" name="a_val">
<input type="hidden" name="b_val">
<input type="hidden" name="c_val">
<input type="hidden" name="answerOne">
<input type="hidden" name="answerTwo">
<input type="hidden" name="Answer">
</body>
</html>
plnkr http://plnkr.co/edit/aaY5rcJ6v0g7bdEEr7h0?p=preview

Failure to calculate the total monthly payment for a car loan. What's going wrong?

Updated code. calculate() still not working. The monthly payment amount is ultimately not being passed to the "total" id box. Does anyone see what the underlying problem is here? My syntax seems to be correct, I believe there may be a problem with my specification of where each variable is applied in the code.
I am having problems getting the function calculate() to pass the correct result in "total." Any possible solutions? The action of clicking the calculate button should display the total, but is displaying nothing at all, as if the button does not activate the calculate function at all.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function calculate() {
var P = document.getElementById("price").value;
var D = document.getElementById("DP").value;
var R = document.getElementById("R").value;
var N = document.getElementById("N").value;
var i = (R / 1200);
var n = (N * 12);
var m = ((P - D) * i * Math.pow(1 + i,n)) / (Math.pow(1 + i,n) - 1);
var result = document.getElementById('total');
result.value = m;}
</script>
</head>
<div align="center">
<hr>
<form name id="Main">
<input type="number" id="price" placeholder="Price of the Car"/>
<br>
<br>
<input type="number" id="DP" placeholder="Down Payment"/>
<br>
<br>
<input type="number" id="R" placeholder="Annual % Rate"/>
<br>
<br>
<input type="number" id="N" placeholder="# of Years Loaned"/>
<br>
<br>
<input type="button" id="calculate" value="Calculate" onclick="javascript:calculate();"/>
<br>
<br>
<input type="number" id="total" placeholder="Total Cost..." readonly=""/>
<br>
<br>
<input type="reset" value="Reset">
</form>
<hr>
</div>
</html>
Use Math.pow() function instead. The ^ operator is not for mathematical power operations (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_XOR and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/pow).
Also, It's result.value = m, not the other way around :)
Also 2: R and M seem undefined to me, you have to initialize those variables with something, like you did with P and D.
Also 3: use chrome dev tools or anything like that. It will make your life much easier. Remember, javascript doesn't mean "no IDE" :D
Unfortunately, your original code will never work, as it has too many errors.
Here is the corrected fiddle for you, please, have a look:
http://jsfiddle.net/q330fqw8/
function calculate() {
var P = document.getElementById("price").value;
var D = document.getElementById("DP").value;
var R = document.getElementById("R").value;
var N = document.getElementById("N").value;
var i = (R / 1200);
var n = (N * 12);
var m = ((P - D) * i * Math.pow(1 + i,n)) / (Math.pow(1 + i,n) - 1);
var result = document.getElementById('total');
result.value = m;
}
I removed id="calculate" in HTML, because of this: Why JS function name conflicts with element ID?
In Javascript, the 4 variables P,D,R,N should be set properly. Finally, this m.value = result; -> result.value = m;
but I guess, you've already corrected some errors in the question. I worked with your original code.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function calculate() {
var P = document.getElementById("price").value;
var D = document.getElementById("DP").value;
var R = document.getElementById("R").value;
var N = document.getElementById("N").value;
var i = (R / 1200);
var n = (N * 12);
var m = ((P - D) * i * Math.pow(1 + i,n)) / (Math.pow(1 + i,n) - 1);
var result = document.getElementById('total');
result.value = m;}
</script>
</head>
<div align="center">
<hr/>
<form id="Main">
<input type="number" id="price" placeholder="Price of the Car" />
<br />
<br/>
<input type="number" id="DP" placeholder="Down Payment" />
<br/>
<br/>
<input type="number" id="R" placeholder="Annual % Rate" />
<br/>
<br/>
<input type="number" id="N" placeholder="# of Years Loaned" />
<br/>
<br/>
<input type="button" value="Calculate Monthly Payment" onclick="calculate();" />
<br/>
<br/>
Total Monthly Payment:<input type="number" id="total" placeholder="Total Cost..." readonly="" />
<br/>
<br/>
<input type="reset" value="Reset" />
</form>
<hr/>
</div>

Make functioning javascript currency converter

Im having trouble with the following code.
Here is the html part
<form name="convert">
Choose which currency you would like to convert the Euro to:
<select id="conversionType">
<option value="polish">Polish Zloty</option>
<option value="ukraine">Ukraine Hryvnia</option>
</select>
</br>
</br>
<hr>
Amount:<input id="amount" type="text" />
<input id="convertButton" type="button" value="Convert->"/>
To:
<input id="answer" type="text" name="answer" readonly="readonly"/>
</form>
and here is the javascript code.
it has been changed and helped before but i cannot see why it is not working
window.onload = initPage;
var euro;
var convert;
function initPage()
{
document.getElementById("convertButton").onclick = calcAnswer;
document.getElementById("conversionType").onchange = calcAnswer;
}
function calcAnswer()
{
//alert(document.getElementById("conversionType").value);
var value1 = document.getElementById("amount").value1;
var conversionType = document.getElementById("conversionType").value1;
//alert(conversionType);
//if(var value = document.getElementById("conversionType").value=="polish");
// document.getElementById("answer").value=value1 * 4.4976;
//else
// document.getElementById("answer").value=value1* 10.43958;
if(conversionType == "polish") {
document.getElementById("answer").value1=value1 * 4.4976;
} else {
document.getElementById("answer").value1=value1 * 10.43958;
}
}
it will not work at all. i dont know why because i think that the theory is sound. any help wpuld be much appreciated
Any time you do this:
document.getElementById("amount").value1
should be this:
document.getElementById("amount").value
no such thing as value1.
Shouldn't this
<pre> document.getElementById("answer").value1 </pre>
be
document.getElementById("answer").value = value1 * 4.4976

Categories

Resources