Result is not showing - javascript

<!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

Related

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

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>

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)
}

Textarea Calculations

I'm trying to have three textareas. The first two are addends and the last is the sum. What's supposed to happen is if your math equation is correct, a paragraph will say true.
Else, it'll say false. However, the paragraph doesn't say anything when I try.
Here's my code:
<textarea id="x"></textarea>
<textarea id="y"></textarea>
<textarea id="z"></textarea>
<script>
var x = document.getElementById('x').innerHTML;
var y = document.getElementById('y').innerHTML;
var z = x + y;
var p = document.getElementById('p');
</script>
<button oclick="if (z = document.getElementById('z').innerHTML) {p.innerHTML = true} else {p.innerHTML = false}">Calculate</button>
<br>
<p id="p"></p>
First attaching the click event to your button from the JS code using addEventListener will be better (avoid the inline-events), then put your code inside, you have to use .value insted of innerHTML to get the value of a textarea.
Note also that you should use double equals == when you want to compare two elements, and because we need to perform a math operations we should cast our values to numbers using Number() method.
Should be something like :
document.getElementById("calculate").addEventListener("click", function() {
var x = Number( document.getElementById('x').value );
var y = Number( document.getElementById('y').value );
var z = x + y;
var p = document.getElementById('p');
if (z == document.getElementById('z').value) {
p.innerText = "true";
} else {
p.innerText = "false";
}
});
<textarea id="x"></textarea>
<textarea id="y"></textarea>
<textarea id="z"></textarea>
<button id="calculate">Calculate</button>
<br>
<p id="p"></p>
first of all, I suggest you to use input here instead of
Second thing is, I would suggest you to use function when you use 'onclick'
Here's the result:
<html>
<body>
<input type='number' placeholder='x: (input number please)' id="x" />
<input type='number' placeholder='y: (input number please)' id="y" />
<input type='number' placeholder='z: (input number please)' id="z" />
<br />
<button onclick="CheckByFormula()">Calculate</button>
<br />
<p>Check result: z=x+y ?</p>
<p id="p"></p>
<script type='text/javascript'>
function CheckByFormula(){
var x = parseInt(document.getElementById('x').value);
var y = parseInt(document.getElementById('y').value);
var z = x + y;
//alert('having these params:\n x='+x+' y='+y+' z='+z);
var p = document.getElementById('p');
z1 = parseInt(document.getElementById('z').value);
alert('z1='+z1+' z='+z);
if(z1 == z){
document.getElementById('p').innerHTML = 'true'
}
else {
document.getElementById('p').innerHTML = 'false';
}
}
</script>
</body>
</html>
https://jsfiddle.net/14pm7ypz/2/

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 Two calculators on one site

Hi i have this code on my site`
<body>
<script>
function calcResult() {
document.getElementById('result').innerHTML = '';
var num1 = new Number(document.getElementById('txt1').value);
var num2 = new Number(document.getElementById('txt2').value);
if (isNaN(num1) || isNaN(num2)) {
alert('One or both inputs are not a number');
} else {
document.getElementById('result').innerHTML = num1 * num2;
}
}
window.onload = function() {
document.getElementById('btnCalc').onclick = calcResult;
}
</script>
<div>
Enter value 1
<input type="text" id="txt1" />
<br />Enter value 2
<input type="text" id="txt2" />
<br />
<button id="btnCalc">Calculate difference</button>
<div id="result"></div>
</div>
<script>
function test() {
document.getElementById('re').innerHTML = '';
var n1 = new Number(document.getElementById('od1').value);
var n2 = new Number(document.getElementById('od2').value);
if (isNaN(n1) || isNaN(n2)) {
alert('One or both inputs are not a number');
} else {
document.getElementById('re').innerHTML = n1 - n2;
}
}
window.onload = function() {
document.getElementById('od').onclick = test;
}
</script>
<div>
Enter value 1
<input type="text" id="od1" />
<br />Enter value 2
<input type="text" id="od2" />
<br />
<button id="od">Calculate difference</button>
<div id="re"></div>
</div>
</body>
The problem is that first form isnt working and the second is working. On my site i want many of these calculator, but i dont know why is not working. I will be gradefull if someone help me find result.
Write all javascript code in one script tag. Try the following code
<body>
<script>
function calcResult(){
document.getElementById('result').innerHTML = '';
var num1 = new Number(document.getElementById('txt1').value);
var num2 = new Number(document.getElementById('txt2').value);
if(isNaN(num1) || isNaN(num2)){
alert('One or both inputs are not a number');
} else {
document.getElementById('result').innerHTML = num1 * num2;
}
}
function test(){
document.getElementById('re').innerHTML = '';
var n1 = new Number(document.getElementById('od1').value);
var n2 = new Number(document.getElementById('od2').value);
if(isNaN(n1) || isNaN(n2)){
alert('One or both inputs are not a number');
} else {
document.getElementById('re').innerHTML = n1 - n2;
}
}
window.onload=function(){
document.getElementById('btnCalc').onclick = calcResult;
document.getElementById('od').onclick = test;
}
</script>
<div>
Enter value 1 <input type="text" id="txt1" /><br />
Enter value 2 <input type="text" id="txt2" /><br />
<button id="btnCalc">Calculate difference</button>
<div id="result"></div>
</div>
<div>
Enter value 1 <input type="text" id="od1" /><br />
Enter value 2 <input type="text" id="od2" /><br />
<button id="od">Calculate difference</button>
<div id="re"></div>
</div>
</body>
If both functions are equal (you just want to execute three diference elements),
use element's Ids as parameters in function argument and call it as often as you wish with any diference Id.
<body>
<script>
<div>
Enter value 1 <input type="text" id="txt1" /><br />
Enter value 2 <input type="text" id="txt2" /><br />
<button id="btnCalc">Calculate difference</button>
<div id="result"></div>
</div>
<script>
function test(id){
document.getElementById(id, id2, id3).innerHTML = '';
var n1 = new Number(document.getElementById(id2).value);
var n2 = new Number(document.getElementById(id3).value);
if(isNaN(n1) || isNaN(n2)){
alert('One or both inputs are not a number');
} else {
document.getElementById(id).innerHTML = n1 - n2;
}
}
window.onload=function(){
document.getElementById('btnCalc').onclick = function(){ test("result", "txt1", "txt2") };
document.getElementById('od').onclick = function(){ test("re", "od1", "od2") };
}
</script>
<div>
Enter value 1 <input type="text" id="od1" /><br />
Enter value 2 <input type="text" id="od2" /><br />
<button id="od">Calculate difference</button>
<div id="re"></div>
</div>
<script type="text/javascript">
function calcResult(resultId, valId, val2Id, operation) {
var $result = document.getElementById(resultId);
$result.innerHTML = '';
var num1 = new Number(document.getElementById(valId).value);
var num2 = new Number(document.getElementById(val2Id).value);
if (isNaN(num1) || isNaN(num2)) {
alert('One or both inputs are not a number');
} else {
$result.innerHTML = operation(num1, num2);
}
}
window.onload = function() {
document.getElementById('btnCalc').onclick = function() {
calcResult('result', 'txt1', 'txt2', function(num1, num2) {
return num1 * num2;
});
}
document.getElementById('od').onclick = function() {
calcResult('re', 'od1', 'od2', function(num1, num2) {
return num1 - num2;
});
};
}
</script>
Put all the scripts in one <script> tag.
Also, there's a room for improvement on your program. see below:
i can see that eventhough your button is named "calculate difference",
the first form is calculating the product and the second form is calculating the difference, thus, using this,
you can rewrite your code in such a way that you only have one function for both operations,
just pass the elementIds as parameters and a function which takes care which operation to apply. like the one I wrote above.
see it here: http://jsfiddle.net/1yo4ypc2/

Categories