javascript calculator not working properly - javascript

hi so i am new to javascript and i am trying to make a simple calculator using HTML and js. However i have run into a problem where i press the button to calculate the answer and it wont do anything. I tried it in an online ide and it just gave me the wrong answer. here is the code can anyone help. thanks--
<!DOCTYPE html>
<html>
<head>
<title>calculator</title>
<script type="text/javascript">
document.getElementById("equals").onclick = function() {
var answer = parseInt(document.getElementById('number_1').value)+ parseInt(document.getElementById('number_1').value);
document.getElementById('answer').innerHTML = answer;
};
</script>
</head>
<body>
<input type="text" name="number_1" id = "number_1">
<p>+</p>
<input type="text" name="number_2" id = "number_2">
<input type="submit" name="equals" id = "equals" value="=">
<p id = "answer"></p>
</body>
</html>

forms including onClick conditions without GET/POST methods , generally use button .
<input type="button" name="equals" id="equals" value="=">
I guess you are adding same variables twice ?
var answer = parseInt(document.getElementById('number_1').value)+ parseInt(document.getElementById('number_2').value);

You're adding the value from the same input twice and you have to set the event handler after the button is created, .
<body>
<input type="text" name="number_1" id = "number_1">
<p>+</p>
<input type="text" name="number_2" id = "number_2">
<input type="submit" name="equals" id = "equals" value="=">
<p id = "answer"></p>
<script type="text/javascript">
document.getElementById("equals").onclick = function() {
var answer = parseInt(document.getElementById('number_1').value)+ parseInt(document.getElementById('number_1').value);
document.getElementById('answer').innerHTML = answer;
};
</script>
</body>

The main problem is you are adding the event click to element equals, but in these moment, element equals doesn't exists.
wrap your document.getElementById into window.onload function to say javascript: "when all the document finish to load, add the event click to element equals"
try this:
window.onload = function () {
document.getElementById("equals").onclick = function() {
var answer = parseInt(document.getElementById('number_1').value, 10)+ parseInt(document.getElementById('number_2').value, 10);
document.getElementById('answer').innerHTML = answer;
};
}
Another important thing I have added ,10 to your parseint, this is to make sure that the conversion is to a number into decimal mode
"The parseInt() function parses a string and returns an integer.
The radix parameter is used to specify which numeral system to be used, for example, a radix of 16 (hexadecimal) indicates that the number in the string should be parsed from a hexadecimal number to a decimal number.
If the radix parameter is omitted, JavaScript assumes the following:
If the string begins with "0x", the radix is 16 (hexadecimal)
If the string begins with "0", the radix is 8 (octal). This feature is deprecated
If the string begins with any other value, the radix is 10 (decimal)"
Source: parseInt use

i fixed it now i had to wrap my code in a window.onload
<!DOCTYPE html>
<html>
<head>
<title>calculator</title>
<script type="text/javascript">
window.onload = function(){
document.getElementById("equals").onclick = function() {
var answer = parseInt(document.getElementById('number_1').value)+ parseInt(document.getElementById('number_2').value);
document.getElementById('answer').innerHTML = answer;
};
};
</script>
</head>
<body>
<input type="text" name="number_1" id = "number_1">
<p>+</p>
<input type="text" name="number_2" id = "number_2">
<button id = "equals">=</button>
<p id = "answer"></p>
</body>
</html>

Related

Use a checkbox to toggle between 2 numbers

How do I use a checkbox in JS/jQuery to toggle just between 2 numbers?
I want unchecked to always be $0 and checked to always be $100. The code below comes close. I'm looking to use str.replace as opposed to switching divs using display:none.
Code:
function myFunction() {
let str = document.getElementById("demo").innerHTML;
document.getElementById("demo").innerHTML = str.replace("$0", "$100");
}
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript String</h2>
<p>The replace() method searches a string for a specified value, or a regular expression,
and returns a new string where the specified values are replaced.</p>
<p id="demo">$0</p>
<input type="checkbox" onclick="myFunction()" value="Try It">
</body>
</html>
function myFunction() {
const element = document.getElementById('demo')
element.innerText = element.innerText === '$0' ? '$100' : '$0'
}

How do I make the input value get verified?

I'm trying to code a basic first degree equation calculator , but my input value is not getting verified can someone help , I appreciate your attention
<!DOCTYPE html>
<head>
<script src="scriptfoda.js" type="text/javascript"></script>
<script>
var eq = Document.getElementById('cu');
var someigual = eq.slipt("=");
function butao() {
if (eq.value.includes("x") && eq.value.includes("=") == false){
eq.innerHTML = "PLEASE PUT X AND = IN THE EQUATION";
}
}
</script>
</head>
<body>
<button type="button" name="button" onclick="butao()">top</button>
<input type="text" size="99" id="cu" placeholder="coloque uma equaçao de 1 grau com 1 icognita">
<p id="error"></p>
</body>
</html>
There are a couple of things that were wrong about your code, so ill provide some feedback on that. When your script initialises, you are trying to get the initial value of eq, but it only ever gets that value the one time, rather than on each click. This should be moved inside butao
Your if statement isn't doing what you think it is, it is checking if it includes x and if it doesnt include =. What i assume you want, is to check that eq.value does include both x and =, so you want to make sure that neither are missing, hence checking if either of them are false, and then putting the error.
You want document.getElementById() not Document.getElementById()
You (most likely) wanted to alter the value of the input, rather than the innerhtml
slipt is not a function, and i assume you mispelt split
function butao() {
var eq = document.getElementById('cu');
var someigual = eq.value.split("=");
if (!eq.value.includes("x") || !eq.value.includes("=")) {
eq.value = "PLEASE PUT X AND = IN THE EQUATION";
}
}
<!DOCTYPE html>
<body>
<button type="button" name="button" onclick="butao()">top</button>
<input type="text" size="99" id="cu" placeholder="coloque uma equaçao de 1 grau com 1 icognita">
<p id="error"></p>
</body>
</html>

simple javascript addition, where am I going wrong?

I'm trying to get it to add the two numbers inputted by the user, and print it inside of the p tag. Any help would be much appreciated. Here's the code:
<html>
<!DOCTYPE HTML>
<meta charset="UTF-8" name="viewport" content="width=device-width">
<head>
<title>Calculator</title>
</head>
<body>
<h2>Enter in the values you want to add</h2>
<form>
<input id="num1" name="num1" type="number"> //value one
</br>
<input id="num2" name="num2" type="number"> //value two
<button id="calculate">Calculate</button> //Click to calculate
</form>
<p id="p">The answer will show here</p>
<script>
var p1=document.getElementById("p");
var p=p1.innerHTML;
var calc=document.getElementById("calculate");
calc.addEventListener("click", answer); //When the button is clicked it calls the function answer()
function answer() {
var num1=document.getElementById("num1");
var num2=document.getElementById("num2");
var x=num1.innerHTML;
var y=num2.innerHTML;
p=x+y; //print the sum of the two values, inside of the p tag
}
</script>
</body>
To decode what's going on in your JavaScript, please see my annotations to the code:
var p1=document.getElementById("p"); // Stores a reference to an element with id "p" to variable p1
var p=p1.innerHTML; // Retrieves the HTML contents of said attribute and assigns it to variable p (not needed)
var calc=document.getElementById("calculate"); // Stores a reference to an element with id "calc" (your button) to variable calc
calc.addEventListener("click", answer); // Attaches an event handler to the element referenced via variable calc
function answer()
{
var num1=document.getElementById("num1"); // Stores a reference to an element with id "num1" in variable num1
var num2=document.getElementById("num2"); // Stores a reference to an element with id "num2" in variable num2
var x=num1.innerHTML; // Retrieves the HTML contents of the element referenced by num1 and stores it in variable x (error)
var y=num2.innerHTML; // Retrieves the HTML contents of the element referenced by num2 and stores it in variable y (error)
p=x+y; // Since both x and y are strings, they are concatenated and the result is stored in variable p (produces wrong result)
// Missing assignment of result to output element
}
The problem: You don't have a statement that actually assigns the result to the paragraph marked with ID "p", instead you are modifying a variable.
Furthermore, since you are retrieving strings from the input fields, the addition is in reality a concatenation, producing a false result (num1.value and num2.value are needed to access the actual values). I'd also suggest converting things to an integer - parseInt does the trick here.
There are several errors in your code, will try to address them one by one:
The <button> by default is type="submit" which when pressed refreshes the whole page, not the intended behaviour. To fix it just need to add type="button", which makes it behabe like a button that by itself does nothing.
The result of p=x+y, you are doing nothing with it. p is just a variable containing the result of the operation, but you need then to insert it inside the <p> tag for it to show up. Adding this at the end of your answer() function should fix it: p1.innerHTML = p;.
The <input> values, those are stored in the value property instead of the innerHTML. So it should look like this var x=num1.value; and var y=num2.value;.
The "sum", in JavaScript the + operator can be used both to add numerical values and to concatenate strings, and the engine chooses what to do guessing by the type of the values you are using, in your case strings. Because even if you type 1 in the input, retrieving it later with .values will return it as a string. You have to cast it back to a number to get the desired result. Just doing this is enought var x=Number(num1.value); and var y=Number(num2.value);.
And that's all.
Here you have your code with the fixes applied.
<html>
<!DOCTYPE HTML>
<meta charset="UTF-8" name="viewport" content="width=device-width">
<head>
<title>Calculator</title>
</head>
<body>
<h2>Enter in the values you want to add</h2>
<form>
<input id="num1" name="num1" type="number"> //value one
</br>
<input id="num2" name="num2" type="number"> //value two
<button type="button" id="calculate">Calculate</button> //Click to calculate
</form>
<p id="p">The answer will show here</p>
<script>
var p1=document.getElementById("p");
var p=p1.innerHTML;
var calc=document.getElementById("calculate");
calc.addEventListener("click", answer); //When the button is clicked it calls the function answer()
function answer() {
var num1=document.getElementById("num1");
var num2=document.getElementById("num2");
var x=Number(num1.value);
var y=Number(num2.value);
p=x+y; //print the sum of the two values, inside of the p tag
p1.innerHTML = p;
}
</script>
</body>
Sorry for the lengthy answer but tried to attack each error by itself and it's explanation as clear and simple as I can do.
p = p1.innerHTML
copies the contents of your paragraph into the variable p.
So your
p = x+y
merely assigns a new value to your variable p and doesn't change the innerHTML of your paragraph.
Try
p1.innerHTML = (x + y) + ''; // + '' converts the result of x + y to a string
You should also use '.value' instead of '.innerHTML' to get the contents of your inputs and then convert them to numbers with parseInt() before adding them.
There were quite a few issues; you can't copy the innerHTML of a p and then assign it a value. You must convert the input values to integers in order to add them. With inputs you can ask for their "value" rather than innerHTML.
<html>
<!DOCTYPE HTML>
<meta charset="UTF-8" name="viewport" content="width=device-width">
<head>
<title>Calculator</title>
</head>
<body>
<h2>Enter in the values you want to add</h2>
<form>
<input id="num1" name="num1" type="number"> //value one
</br>
<input id="num2" name="num2" type="number"> //value two
<button id="calculate">Calculate</button> //Click to calculate
</form>
<p id="p">The answer will show here</p>
<script>
var p1=document.getElementById("p");
var calc=document.getElementById("calculate");
calc.addEventListener("click", answer); //When the button is clicked it calls the function answer()
function answer(e) {
e.preventDefault();
var num1=document.getElementById("num1");
var num2=document.getElementById("num2");
var x=parseInt(num1.value, 10);
var y=parseInt(num2.value, 10);
p1.innerHTML = x+y; //print the sum of the two values, inside of the p tag
}
</script>
</body>
</html>

Trouble Getting HTML Input Into JS

So, I'm trying to build a decimal to binary converter for my computer science class. I already made an algorithm in Python that seems to be working pretty well. It works in the Javascript console perfectly fine too. I'm now at a point trying to accept input from an HTML form. I'm kind of a DOM noob, but I thought this would be something easy and fun to do, but it's turning out that it's a lot more confusing than I thought. I would know how to do this in React.js, but I'm trying to use this as a learning experience. Basically, I want to take input from a form, run it through a function and have the returned value of the function back into HTML. I know how to get the value into HTML, but I have no clue how to retrieve the form data into Javascript. Here's a Codepen with my progress so far.
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Javascript Binary Calculator</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<center><form style="margin-top: 25%" id="myForm">
<input type="text" class="form-control" style="width: 250px" placeholder="Type a number!" id="textForm">
<br />
<input type="button" class="btn" style="margin-top: 15px" value="Submit">
</form></center>
<script
src="https://code.jquery.com/jquery-2.2.4.min.js"
integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
crossorigin="anonymous"></script>
<script src="script.js" type="text/javascript"></script>
</body>
</html>
Javascript:
function conversion(){
var quotient = 15;
var convertedNum = [];
if (formValue == 0){
convertedNum = [0]
}
while(formValue >= 1){
quotient = formValue/2;
var mod = formValue %2;
formValue = quotient;
convertedNum.push(mod);
convertedNum.reverse();
}
console.log(convertedNum.join(""));
}
$('#textForm').change(function(){
var formValue = document.getElementById('#textForm').value;
parseInt(formValue);
console.log(formValue);
console.log("It's Working in Console!");
conversion();
});
Her's a simple way doing what you are trying to accomplish.
function myFunction() {
var x = document.getElementById("myText").value;
document.getElementById("demo").innerHTML = x;
}
</script>
<body>
First Name: <input type="text" id="myText" >
<p>Click the button to display the value of the value attribute of the text field.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
You want to put the answer back onto the page to be displayed when they click submit?
First you'll need a container (well, you can create one on the fly in Javascript, but typically you would just create an empty div container to hold the answer).
Add a div container for the solution: (after form probably)
<div id="convertedToBinary" class="answerDiv"></div>
It looks like you're using jQuery, which makes entering HTML into a target easy.
Add this to your conversion function:
$('#convertedToBinary').html(formValue+" converted to binary is: "+convertedNum.join("") );
<head>
<title></title>
<script
src="https://code.jquery.com/jquery-2.2.4.min.js"
integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
crossorigin="anonymous"></script>
</head>
<body>
<input type="text" class="form-control" />
<span id="result"></span>
<script>
var formValue;
function conversion()
{
var quotient = 15;
var convertedNum = [];
if (formValue == 0)
{
convertedNum = [0]
}
while (formValue >= 1)
{
quotient = parseInt(formValue / 2);
var mod = formValue % 2;
formValue = quotient;
convertedNum.push(mod);
convertedNum.reverse();
}
$('#result').html(convertedNum.join(""));
}
$('.form-control').keydown(function ()
{
var $this = $(this);
setTimeout(function ()
{
formValue = $this.val();
conversion();
}, 100);
});
</script>
</body>
</html>
Just a couple of hints starting from the HTML / JS you provided:
You are using a jQuery selector within plain JS, so this won't work:
var formValue = document.getElementById('#textForm').value;
Change that to
var formValue = document.getElementById('textForm').value;
if you want to use plain JavaScript - or do it the jQuery way, like so
var formValue = $('#textForm').value;
You could also have stored the reference to that DOM element in a var, up front, and then work on that, but that's another topic.
Also you must pass the formValue to the conversion function, like so
conversion(formValue);
otherwise you can't work with the input value within the function scope.
All that remains to do is writing the resulting value into the innerHTML of some . The other answers give you two options for doing that - in jQuery (innerHTML) or plain old JavaScript.

External JavaScript file issues

Now this is just for reference for a future project but I am trying to call a function that reads in a string but displays a float after. So I first check the string then display a random number. The problem I am having, I think, is with the document.getElementById part. Any suggestions??
HTML File:
<html>
<body>
<input type="text" id="letter" value=""/><br/>
<input type="button" value="LETS DO THIS!" onclick="floatNum();"/></br>
<script type="text/javascript" src="letNum.js"></script>
</body>
</html>
External JS File:
function floatNum()
{
var val1 = document.getElementById("letter");
if (isNaN(val1)
{
alert(Math.random())
}
}
the following code is working:-
in your code,you missed closing parenthesis ")" near to "if condition"
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>demo</title>
<script type="text/javascript">
function floatNum()
{
var letter = document.getElementById("letter");
if (isNaN(letter.value))// using input fields value not the whole object
{
alert(Math.random());
}
}
</script>
</head>
<body>
<input type="text" id="letter" value="" /><br />
<input type="button" value="LETS DO THIS!" onclick="floatNum();" />
</body>
</html>
Yes, you want to pass in the element in the function, like so:
<input type="button" value="LETS DO THIS!" onclick="floatNum(document.getElementById('letter'))"/></br>
And in your JS
function floatNum(el)
{
if (isNaN(el)
{
alert(Math.random())
}
}
In case of a reusable function - try not to make it dependent on your DOM. Think about what would happen if you rename your element or want to use this function again. You couldn't before - now you can.
The problem is on this line:
var val1 = document.getElementById("letter");
It should be:
var val1 = document.getElementById("letter").value;
The first sets val1 to the DOM element representing the input tag, the second sets it to the text value of the input tag (its contents).
You need to process the value of input field not the input field itself.
function floatNum()
{
var letter = document.getElementById("letter");
if (isNaN(letter.value) // using input fields value not the whole object
{
alert(Math.random())
}
}
You don't grab the value of the input, but the input itself.
Correct code would be :
var val1 = document.getElementById("letter").value;

Categories

Resources