Javascript, Chrome don't recognise the variable outside the function - javascript

I hope you are well!!
Recently I created this calculator following a tutorial on youtube.
How you can see below I put all the variable outside the function.
In Firefox is working fine, but if I use Google Chrome and I try to use it, is giving me the result of NaN..... I fixed this error moving the var inside the function, but I don't understand why with Chrome I have to move it inside and Firefox no....
If anyone would be able to give me an explanation I will really appreciate!
Thanks!!!!
var value1 = parseInt(document.querySelector("#textbox1").value);
var value2 = parseInt(document.querySelector("#textbox2").value);
var operator = document.querySelector("#operators").value;
var total = document.getElementById("total");
var calculate;
function result() {
if (operator === "add") {
calculate = value1 + value2;
} else if (operator === "sub") {
calculate = value1 - value2;
} else if (operator === "multiply") {
calculate = value1 * value2;
} else if (operator === "divide") {
calculate = value1 / value2;
}
total.innerHTML = calculate;
}
<form>
<input type="text" id="textbox1">
<input type="text" id="textbox2"><br>
<select id="operators">
<option value="add">Add</option>
<option value="sub">Sub</option>
<option value="multiply">Multiply</option>
<option value="divide">Divide</option>
</select>
<input type="button" id="confirm" value="Result" onclick="result()">
<div id="total"></div>
</form>

The problem is you're grabbing the values before the user fills them in, right away, when the page loads. (You've said it's "working" in Firefox. It doesn't for me, but if you have autofill enabled, it may be filling in values from a previous run.)
Instead, grab the values within the result function:
var total = document.getElementById("total");
function result() {
var value1 = parseInt(document.querySelector("#textbox1").value);
var value2 = parseInt(document.querySelector("#textbox2").value);
var operator = document.querySelector("#operators").value;
var calculate;
if (operator === "add") {
calculate = value1 + value2;
} else if (operator === "sub") {
calculate = value1 - value2;
} else if (operator === "multiply") {
calculate = value1 * value2;
} else if (operator === "divide") {
calculate = value1 / value2;
}
total.innerHTML = calculate;
}
<form>
<input type="text" id="textbox1">
<input type="text" id="textbox2"><br>
<select id="operators">
<option value="add">Add</option>
<option value="sub">Sub</option>
<option value="multiply">Multiply</option>
<option value="divide">Divide</option>
</select>
<input type="button" id="confirm" value="Result" onclick="result()">
<div id="total"></div>
</form>

Related

Concatenate two different select/option tag to able to calculate in JavaScript

I try to make some calculating method in Js for calculate the perimeter and the area of the square/rectangle.
I failed somewhere in the options when I pick the different methods.
I want to work when I choose square of the area or perimeter to calculate after I apply the input fields with two different number.
I also try to hide the second input field when I only choose the square option, but I could not do it.
So any helpful suggestion to how to fix my code to work properly?
function calc() {
var num1 = parseInt(document.getElementById("num1").value);
var num2 = parseInt(document.getElementById("num2").value);
var typ = document.getElementById("type").value;
var squarePerimeter = num1 * num1;
document.getElementById("perimeter").value = squarePerimeter;
var squareArea = num1 * 4;
document.getElementById("area").value = squareArea;
var rectanglePerimeter = num1 * num2;
document.getElementById("perimeter").value = rectanglePerimeter;
var rectangleArea = 2 * num1 + num2;
document.getElementById("area").value = rectangleArea;
if (typ === "sqr") {
document.getElementById("result").value = squarePerimeter;
} else if (typ === "rect") {
document.getElementById("result").value = rectanglePerimeter;
} else if (typ === "sqr") {
document.getElementById("result").value = squareArea;
} else if (typ === "rect") {
document.getElementById("result").value = rectangleArea;
}
};
<select name="" id="type">
<option id="square" value="sqr">square</option>
<option id="rectamgle" value="rect">rectangle</option>
</select>
<select name="" id="calculating">
<option id="perimeter" value="perimeter">Perimeter</option>
<option id="area" value="area">Area</option>
</select>
<br>
<input type="number" id="num1">
<input type="number" id="num2">
<br>
<button type="button" onclick="calc()">Calculate</button>
<input type="number" id="result">
Following your code structure you should change some things, like yoiur elseif, your are setting the same conditions as previous ifs, they will never be true.
function calc() {
var num1 = parseInt(document.getElementById("num1").value);
var num2 = parseInt(document.getElementById("num2").value);
var typ = document.getElementById("type").value;
var obj = document.getElementById("calculating").value;
if (typ === "sqr" && obj === "area") {
document.getElementById("result").value = num1 * num1;
} else if (typ === "rect" && obj === "area") {
document.getElementById("result").value = num1 * num2;
} else if (typ === "sqr") {
document.getElementById("result").value = num1 * 4;
} else if (typ === "rect") {
document.getElementById("result").value = 2 * (num1 + num2);
}
};
function toggleNum2() {
var typ = document.getElementById("type").value;
var num2 = document.getElementById("num2");
if (typ === "sqr") {
num2.style.display = "none";
} else {
num2.style.display = "inline-block";
}
};
<body onload="toggleNum2()">
<select name="" id="type" onchange="toggleNum2()">
<option id="square" value="sqr">square</option>
<option id="rectamgle" value="rect">rectangle</option>
</select>
<select name="" id="calculating">
<option id="perimeter" value="perimeter">Perimeter</option>
<option id="area" value="area">Area</option>
</select>
<br>
<input type="number" id="num1">
<input type="number" id="num2">
<br>
<button type="button" onclick="calc()">Calculate</button>
<input type="number" id="result">
</body>
Other question!
How I can easily implement this code as work as the same in jQuery?

Performing arithmetic operations on two inputs in JavaScript

I am trying to add two numbers that a user enters, and returning the sum, difference, product or the quotient of two values the user enters. For that, I made two inputs with a drop-down list between that. The drop down list has options to add, subtract, multiply and divide. What I am trying to do is perform the operation the user attempts to perform. You can see a demo here.
//Variables
let firstNum = document.getElementById("num1");
let secondNum = document.getElementById("num2");
let result = document.getElementById("result");
//Event Listeners
firstNum.addEventListener("input", mainFunction());
secondNum.addEventListener("input", mainFunction());
result.addEventListener("input", mainFunction());
//Main JavaScript
function mainFunction() {
if (document.getElementById("options").options[0]) {
var one = parseFloat(firstNum.value) || 0;
var two = parseFloat(secondNum.value) || 0;
result.innerHTML = one+two;
}
}
* {
font-family: helvetica;
text-align: center;
}
<h1>Calculator</h1>
<form>
<input type="number" id="num1" placeholder="First Number"/>
<select id="options">
<option id="addition">+</option>
<option id="subtraction">−</option>
<option id="multiplication">✖</option>
<option id="division">÷</option>
</select>
<input type="number" id="num2" placeholder="Second Number"/>
<p id="result"></p>
</form>
Please inform me if you find any errors.
Thanks.
I have changed your code, the new version is here http://jsfiddle.net/v56fkaww/6/
The error was that you should encapsulate the call of function into an anonymous function
//Event Listeners
firstNum.addEventListener("input",function(){mainFunction()});
secondNum.addEventListener("input",function(){mainFunction()});
Everything seems to be fine except for a small problem :
firstNum.addEventListener("input", mainFunction());
should be :
firstNum.addEventListener("input", mainFunction);
Since the function is already defined and this expects a function so you only need to pass a reference to the function.
Code :
I added functionality for all four operators and shortened the code a bit
//Variables
let firstNum = document.getElementById("num1"),
secondNum = document.getElementById("num2"),
result = document.getElementById("result");
//Event Listeners
firstNum.addEventListener("input", mainFunction);
secondNum.addEventListener("input", mainFunction);
result.addEventListener("input", mainFunction);
//Main JavaScript
function mainFunction() {
var one = +firstNum.value||0; // convert to number
var two = +secondNum.value||0; // convert to number
var opt = document.getElementById("options");
// this is the shorter than what you are using
result.innerHTML = opt.options[0] ? one + two : opt.options[1] ? one - two : opt.options[2] ? one * two : one / two;
}
* {
font-family: helvetica;
text-align: center;
}
<h1>Calculator</h1>
<form>
<input type="number" id="num1" placeholder="First Number"/>
<select id="options">
<option id="addition">+</option>
<option id="subtraction">−</option>
<option id="multiplication">✖</option>
<option id="division">÷</option>
</select>
<input type="number" id="num2" placeholder="Second Number"/>
<p id="result"></p>
</form>
There is also a non standard way to evaluate operator without the need of performing a switch or if , this is using a Function constructor and execute inmediate. result.innerHTML = (new Function("return "+one+operator+two))();
//Variables
let firstNum = document.getElementById("num1");
let secondNum = document.getElementById("num2");
let result = document.getElementById("result");
let operator = document.getElementById("options").value;
//Event Listeners
//You should asign the function itself not the result like mainFunction()
firstNum.addEventListener("input", mainFunction);
secondNum.addEventListener("input", mainFunction);
result.addEventListener("input", mainFunction);
//All of this is like something.addEventListener("input", function(){//code});
function mainFunction() {
var one = parseFloat(firstNum.value) || 0;
var two = parseFloat(secondNum.value) || 0;
//evaluate the operator as a javascipt operator not just as string
result.innerHTML = (new Function("return "+one+operator+two))();
}
<td><input type="number" class="form-control text-center tot" id="input1"></td>
<td id="mark" class="text-center"></td>
<td><input type="number" class="form-control text-center tot" id="input2"></td>
<td id="total" class="text-center"></td>
function inputOper(operaterName) {
let input1 = Number($('#input1').val());
let input2 = Number($('#input2').val());
let result = $('#total');
if(operaterName == 'add'){
result = input1 + input2;
$('#mark').html('+');
}else if(operaterName == 'sub'){
result = input1 - input2;
$('#mark').html('-');
}else if(operaterName == 'mul'){
result = input1 * input2;
$('#mark').html('*');
}else if(operaterName == 'div'){
result = (input1 / input2).toFixed(2);
$('#mark').html('/');
}
$('#total').html(result)
}

Javascript doesnt work without syntax error

This is JavaScript code:
<script type="text/javascript">
function Choose() {
var n1, Price, Stock;
n1 = document.getElementById("product").value;
if (n1 == "1")
Price = 12.5;
Stock = 15;
else
Price = "40";
Stock = "5";
document.getElementById("price") = Price;
document.getElementById("stock") = Stock;
}
< /script
In the body of HTML:
<select id="product"><option value="1" >PRODUCT 1</option>
<option value="2">PRODUCT 2</option> </select
<input type="button" value="Submit" onclick="Choose()">
<input type="text" value="0" id="price">
<input type="text" value="0" id="stock">
I need help!Why this code doesn't work?
Where is my failure?
You need to set the value of the DOM element
document.getElementById("price").value = Price;
document.getElementById("stock").value = Stock;
You need to set the attribute value of the DOM element and not the DOM element itself to an integer value
Also you are missing {} around the if-else block. I am assuming that you missing the > operator while closing the script tag is a typo and not in the original code. If its there change it in the original code too
<script type="text/javascript">
function Choose() {
var n1, Price, Stock;
n1 = document.getElementById("product").value;
if (n1 == "1") {
Price = 12.5;
Stock = 15;
}
else {
Price = "40";
Stock = "5";
}
document.getElementById("price").value = Price;
document.getElementById("stock").value = Stock;
}
< /script>
function Choose() {
var n1, Price, Stock;
n1 = document.getElementById("product").value;
if (n1 == "1") {
Price = "12.5";
Stock = "15";
} else {
Price = "40";
Stock = "5";
}
document.getElementById("price").value = Price;
document.getElementById("stock").value = Stock;
}
<select id="product">
<option value="1" >Product1</option>
<option value="2">Product2</option>
</select>
<input type="button" value="Submit" onClick="Choose()">
<input type="text" id="price"/>
<input type="text" id="stock"/>
First of all it might not be the case but you are missing the end tag of the script.
</script>
Secondly you are also missing the brackets for the if and else statements.
if (n1=="1"){
Price=12.5;
Stock=15;
}
else{
Price="40";
Stock="5";
}
Hope it helps!
Br,
José Sousa
<script type="text/javascript">
function Choose(){
var n1,Price,Stock ;
n1 = document.getElementById("product").value;
if (n1 == "1") {
Price = 12.5;
Stock = 15;
}
else {
// place it in block
Price = "40";
Stock = "5";
} // place it in block
document.getElementById("price").value = Price;
document.getElementById("stock").value = Stock;
}
</script>
Assume that the error you get is misplaced else.
If more than one statements are written under condition or loop, it must be made as block

Javascript Drop Down Menu Currency Converter

Hello everyone I need you guys help with this
It's suppose to convert the value you entered after you choose an option and click convert.
HTML CODE:/(I'm not sure how to use drop down menus with java script)
<html>
<body>
<form>
<select name="converts" id="Selection">
<option>Chose Option</option>
<option value="1" >Currency 1 to Currency2</option>
<option value="2" >Currency 2 to Currency1</option>
</select>
<br><br>
Value <input type="text" id="value"><br>
Conversion <input type="text" id="conversion"><br><br>
<input type="Button" onclick="Conversion()" value="Convert">
</form>
</body>
</html>
JAVASCRIPT CODE:
<script type="text/javascript">
function Conversion()
{
var val = document.getElementById ("value").value;
var madeSelection = document.getElementById ("Selection").value;
if(madeSelection==1( var ans= +value * 1.37); )){
if(madeSelection==2 ( var ans= +value * 1.30; )){
}
}
conversion.value = ans;
}
</script>
There are several problems that are causing this to be non-functional:
You declare a variable called val that you are not using. Everywhere else in your code, it is called value.
var val = document.getElementById ("value").value;
Older browsers may not deal with a value property of a select element
var madeSelection = document.getElementById ("Selection").value;
Your if statements are malformed (and nested for some reason), and some of the operations are weird.
if(madeSelection==1( var ans= +value( 0.37); )){
if(madeSelection==2 ( var ans= +value * 0.30; )){
...
When properly formatted, your code is:
if (madeSelection == 1(var ans = +value(0.37);)) {
if (madeSelection == 2(var ans = +value * 0.30;)) {
if (madeSelection == 3(var ans = +value * 2.70;)) {
if (madeSelection == 4(var ans = +value * 0.80;)) {
if (madeSelection == 5(var ans = +value * 3.38;)) {
if (madeSelection == 6(var ans = +value * 1.25;)) {}
}
}
}
}
}
When more properly written, it should be:
if (madeSelection == 1) {
var ans = +value(0.37);
}
if (madeSelection == 2) {
var ans = +value * 0.30;
}
if (madeSelection == 3) {
var ans = +value * 2.70;
}
if (madeSelection == 4) {
var ans = +value * 0.80;
}
if (madeSelection == 5) {
var ans = +value * 3.38;
}
if (madeSelection == 6) {
var ans = +value * 1.25;
}
although:
the ans variable, along with all of your other variables should be declared at the top of the function (because that's where they're actually declared anyway, look up variable hoisting).
I'm not sure why you're prefixing the righthand assigment with the +.
value is not a function, but you're apparently attempting to use it as one if madeSelection == 1.
Finally, you're referencing a variable called conversion which has not been defined. This will still probably work as you have an input with an id of conversion and most (but not all) browsers will store the id as a global variable pointing to the element.
Also, when you have many if statements, you may wan't to consider using a switch statement instead.
All together, it should look more like this:
function Conversion() {
var value = document.getElementById("value").value,
conversion = document.getElementById("conversion"),
madeSelection = document.getElementById("Selection"), // get the select
selection = madeSelection.options[madeSelection.selectedIndex].value, // get the selected option
ans = 0;
value = parseFloat(value);
if (!isNaN(value)) {
switch (selection) {
case "6":
ans = value * 1.25;
break;
case "5":
ans = value * 3.38;
break;
case "4":
ans = value * 0.8;
break;
case "3":
ans = value * 2.7;
break;
case "2":
ans = value * 0.3;
break;
case "1":
ans = value * 0.37;
break;
default:
ans = 0;
break;
}
}
conversion.value = ans;
}
<select name="converts" id="Selection">
<option>Choose Option</option>
<option value="1" >EC to US</option>
<option value="2" >EC to Euro</option>
<option value="3" >US to EC</option>
<option value="4" >US to Euro</option>
<option value="5" >Euro to EC</option>
<option value="6" >Euro to US</option>
</select>
<br />
<label for="value">Value</label>
<input type="text" id="value"><br>
<label for="conversion">Conversion</label>
<input type="text" id="conversion"><br><br>
<input type="Button" onclick="Conversion()" value="Convert">
This should work for you:
function Conversion() {
var val = document.getElementById("value").value,
madeSelection = document.getElementById("Selection").value,
ans
if (madeSelection == 1) ans = val * 0.37;
if (madeSelection == 2) ans = val * 0.30;
if (madeSelection == 3) ans = val * 2.70;
if (madeSelection == 4) ans = val * 0.80;
if (madeSelection == 5) ans = val * 3.38;
if (madeSelection == 6) ans = val * 1.25;
document.getElementById("conversion").value = ans;
}
<form>
<select name="converts" id="Selection">
<option>Chose Option</option>
<option value="1">EC to US</option>
<option value="2">EC to Euro</option>
<option value="3">US to EC</option>
<option value="4">US to Euro</option>
<option value="5">Euro to EC</option>
<option value="6">Euro to US</option>
</select>
<br>
<br>Value
<input type="text" id="value">
<br>Conversion
<input type="text" id="conversion">
<br>
<br>
<input type="Button" onclick="Conversion()" value="Convert">
</form>
Instead a lot IF statements you should use SWITCH.
This is the right way
JS
function Conversion()
{
var val = parseInt(document.getElementById ("value").value);
var madeSelection = parseInt(document.getElementById ("Selection").value);
switch(madeSelection)
{
case 1:
var converted = val * 0.37; //EC to US
break;
case 2:
var converted = val * 0.30; //EC to EUR
break;
case 3:
var converted = val * 2.70; //US to EC
break;
//ETC....
default:
alert('You chose wrong option'); // if user chose wrong option, send him message
break;
}
document.getElementById ("conversion").value = converted;
return false; //prevent for submit form
}
Here is fiddle : http://jsfiddle.net/1cdkvpms/

Result is not showing

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var result = document.getElementById('answer').value;
if (document.getElementById('add')) {
function myFunction() {
add1 = document.getElementById('num1').value;
add2 = document.getElementById('num2').value;
ans = (parseInt(add1)+parseInt(add2));
result.innerHTML = ans;
}
}
</script>
</head>
<body>
<input type="text" id="num1" />
<select id="problem">
<option id="add">+</option>
<option id="sub">-</option>
<option id="mul">x</option>
<option id="div">÷</option>
</select>
<input type="text" id="num2" />
<br />
<input type="submit" onclick="myFunction();" />
<br />
<input type="text" id="answer" readonly />
</body>
</html>
I'm trying to make a sum solver by taking the values from the two text boxes and after clicking the button, it should post the result in the text box below. However it is not doing that.
I also want the program to change how a problem is solved using the dropdown menu with the mathematical symbols.
Thanks.
I think you're after something like this
function myFunction() {
var result = document.getElementById('answer'),
operator = document.getElementById('problem').value,
add1 = document.getElementById('num1').value,
add2 = document.getElementById('num2').value,
ans = 0;
switch (operator) {
case '+':
ans = (parseInt(add1) + parseInt(add2));
break;
case '-':
ans = (parseInt(add1) - parseInt(add2));
break;
case 'x':
ans = (parseInt(add1) * parseInt(add2));
break;
case '÷':
ans = (parseInt(add1) / parseInt(add2));
break;
}
result.value = ans;
}
instead of using if statements, and creating different functions, just have one function and determine the operand.
Edit: Also, watch out for your variable declarations. 'ans', 'add1' and 'add2' weren't being declared which resulted in global variables being created
The problem should be with the line
var result = document.getElementById('answer').value;
Try the below snippet
var result=document.getElementById('answer');
ans = (parseInt(add1)+parseInt(add2));
result.value=ans;
http://jsfiddle.net/2W5za/1/
You have a few issues. Not sure what you were going for with the if but remove it. Also, set the value of a textbox with value not innerHTML.
function myFunction() {
var result = document.getElementById('answer');
add1 = document.getElementById('num1').value;
add2 = document.getElementById('num2').value;
ans = (parseInt(add1)+parseInt(add2));
result.value = ans;
}
http://jsfiddle.net/LjqMJ/
Regarding the first part of the question (and that for which this question is titled), one problem I see is this line of code right here:
var result = document.getElementById('answer').value;
What is the type of result? Later on you treat it as if it is a DOMElement with result.innerHTML = ans; by assuming it has a property innerHTML. However because you used .value it's in fact a string which will not have innerHTML.
Regarding the second part, you can assert which function is selected in the <select> by looking at it's .value. The <option> tags will always exist, regardless of if they are selected or not.
Speaking more broadly, I highly recommend you check out using the debugger in either chrome or firefox. That will allow you to drop a breakpoint in your code, and figure out if the value is being computed correctly, and see what it is attempting to write to, all interactively.
Chrome:
https://developers.google.com/chrome-developer-tools/docs/javascript-debugging
Firefox:
https://developer.mozilla.org/en-US/docs/Tools/Debugger
<!DOCTYPE html>
<html>
<head></head>
<body>
<input type="text" id="num1" />
<select id="problem">
<option value="add">+</option>
<option value="sub">-</option>
<option value="mul">x</option>
<option value="div">%</option>
</select>
<input type="text" id="num2" />
<br />
<input type="submit" onclick="myFunction();" />
<br />
<input type="text" id="answer" readonly />
<script type="text/javascript">
function myFunction()
{
var e = document.getElementById("problem");
var sOperation = e.options[e.selectedIndex].value;
add1 = document.getElementById('num1').value;
add2 = document.getElementById('num2').value;
var ans;
if (!isNaN(add1) && !isNaN(add2)){
if(sOperation=='add'){
//Add
ans = parseInt(add1)+parseInt(add2);
} else if (sOperation=='sub') {
//Subtract
ans = parseInt(add1)-parseInt(add2);
} else if (sOperation=='mul') {
//Multiple
ans = parseInt(add1) * parseInt(add2);
} else if (sOperation=='div') {
//Divide
ans = parseInt(add1) / parseInt(add2);
}
document.getElementById("answer").value = ans;
} else {
alert("Please enter numeric values only");
return false;
}
}
There are many things wrong with your code. However, to fix your problem, change = ans to = ans.toString();
You see, in javascript integers and strings cannot change to each other's values without a conversion (kind of like a brother and sister refusing to share), so toString() is used for a conversion to String.
The other thing to change is innerHTML to value, because you are dealing with text boxes.
HTML
<input type="text" id="num1" />
<select id="problem">
<option id="add">+</option>
<option id="sub">-</option>
<option id="mul">x</option>
<option id="div">÷</option>
</select>
<input type="text" id="num2" />
<br />
<input type="submit" onclick="myFunction();" />
<br />
<input type="text" id="answer" readonly />
JavaScript
function myFunction() {
var result = document.getElementById('answer');
var operator = document.getElementById('problem').value;
var add1 = document.getElementById('num1').value;
var add2 = document.getElementById('num2').value;
var ans;
if (!isNaN(add1) && !isNaN(add2)) {
//Addition
if (operator == '+')
{
ans = (parseInt(add1) + parseInt(add2));
}
//Subtraction
else if (operator == '-') {
ans = (parseInt(add1) - parseInt(add2));
}
//Multiplication
else if (operator == 'x') {
ans = (parseInt(add1) * parseInt(add2));
}
//Division
else if (operator == '÷') {
ans = (parseInt(add1) / parseInt(add2));
}
//Result
result.value = ans;
} else {
alert("Please enter numeric values only");
return false;
}
}
Fiddle Demo

Categories