simple javascript addition, where am I going wrong? - javascript

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>

Related

At first it said its not a function, now its just not doing anything

Okay, I'm trying to make a cheesy accent generator to practice with RegEx. But I have a strange problem that seems unrelated to RegEx. The submit button doesn't do anything. At first the function "maccent" was just called "accent" and at that time the console said "accent" was not a function. With nothing better to go on, I assumed it was because the word "accent" was used so many other times, so I changed the function name to "maccent". Now, however, nothing happens. What's the deal? Here is my code:
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="UTF-8">
<title>Accent Generator</title>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
</head>
<body>
<p>Choose an accent</p>
<input type = "text">
<form action="">
<input type="radio" name="accent" value="German"> German<br>
<input type="radio" name="accent" value="English"> English<br>
<input type="radio" name="accent" value="Indian"> Indian
</form>
<button type="submit" onclick = "maccent()">Submit</button>
<div id = "accented"></div>
<script>
var accent = $('input[name="accent"]:checked').val();
function maccent()
{
if (accent == "German")
{
germAcc();
}
}
function germAcc()
{
var sample = $("input").val()
var desire = sample.replace(/[w]/gi, "v")
//not if it's at the end of a word
var desire2 = desire.replace(/th/, "z")
//replace h too, but not with another z.
//wait, what? It replaces t even if its not followed by h
var desire3 = desire2.replace(/er/, "a")
//this is going to be a hard one
//er is replaced with a but only if its followed by a space or a punctuation
mark.
console.log(desire3);
}
function indAcc()
{
var sample = $("input").val()
var desire = sample.replace(/[r]/gi, "d")
//not if it's at the end of a word
//this words, but not on each indivual word
console.log(desire);
}
function itAcc()
{
}
function britAcc()
{
var sample = $("input").val();
var desire = sample.replace(/[a]/gi, "au")
var desire2 = desire.replace(/er/, "a")
//this is going to be a hard one
console.log(desire2);
//not if it's at the end of a word
}
</script>
</body>
</html>
The problem is the assignment of the "variable" accent. You are doing it at global scope (the top level), so it gets assigned when the page is first loaded.
If you move that assignment into the function maccent() (and move the work "mark" back into the comment it belongs to), your page will work.
Incidentally, the old problem was that you had a function and a variable trying to share the name accent. The variable was "winning".

javascript calculator not working properly

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>

Better way to apply javascript scripts

Hello SO I'm relatively new to html and javascript and I currently want to make a page that will fulfill certain operations such as finding the max number of an array of numbers and factorial of a number as shown below.
and here is how I am organizing these sections
<!DOCTYPE html>
<html lang = "en">
<head>
<title>HTML/CSS Responsive Theme</title>
<meta charset = "utf-8">
<link rel = "stylesheet" href = "main.css" type = "text/css">
<meta name = "viewport" content = "width=device-width, initial-scale=1.0">
<script>
function startFactorial(number)
{
function factorial(num)
{
if(num <= 1)
return 1;
return num * factorial(num - 1);
}
document.factorials.factorialsfield.value = factorial(number);
}
function startMaxofFive(str)
{
//can actually find the max of n numbers not limited to 5
function maxoffive(string)
{
var nums = (string.match(/[-]?\d+/g));
var b = nums.map(Number);
return Math.max.apply(Math,b);
}
document.mof.moffield.value = (maxoffive(str));
}
</script>
</head>
<body>
<section id = "first">
<h3>Factorial</h3>
<form name= "factorials">
Enter a number <input type = "number" name = "factorialsfield" value = 0>
<br><br>
<input type = "button" onClick = "startFactorial(factorialsfield.value)" value = "Calculate"/>
</form>
</section>
<br>
<section id = "second">
<h3>Max of Five Numbers</h3>
<form name = "mof">
Enter 5 numbers <input type = "text" name = "moffield" placeholder = " separate each number by commas" size = 26>
<br><br>
<input type = "button" onClick = startMaxofFive(moffield.value) value = "Calculate"/>
</form>
</section>
<br>
<section id = "third">
<h3>Sum and Multiply</h3>
<form name = "operations">
Enter numbers to apply operations <input type = "text" name = "operationsfield"
</form>
</section>
</body>
</html>
What I wanted to ask you all is is there a better way to access those functions in my script without having to create another function just to use them?
Here's some suggestions:
You can use document.getElementById( id ) to get specific elements where id is the HTML's element id <element id="id_name">.
Events allow you to trigger actions based on user input. It works basically the same, but you no longer need to name the functions: element_variable.event = function() { /* ... */ }
See if the inner functions are really neccessary; see if you can edit the code where you no longer need that function (document.getElementById will probably be able to let you do that stuff)
Example:
<form id="factorials" name="factorials">
<!-- Skipping input -->
<input type="submit" <!-- ... -> />
</form>
// Javascript file
var fact = document.getElementById( "factorials" );
fact.onsubmit = function() {
/* Your code here */
}
It's generally considered best practice to move scripts to the bottom of the page before the closing body tag. This way the loading of the scripts won't interfere with page load.
You can also move your scripts to a separate file and include it:
<script src="myscripts.js"></script>
This will help keep your code more neat and organized.
You always use functions to call functions. Sounds weird but thats how it is :P
You can remove the JS calls from your DOM by adding eventlisteners to your JavaScript file just like this example:
<script>
var x = document.getElementById('test');
x.addEventListener('click', function(){
// your function magic happens here
});
</script>
<div id="test"></div>
Sorry if I understood your question wrong
I am not sure that this is what you asked for, however, it seemed like you wanted to know about other methods to get access to your javascript code or script in your HTML.
I can truly recommend you, to look into Angular for this. With Angular you can call methods in your controller, and scope data between your view (HTML) and controller (Javascript).
https://angularjs.org/
But this is just one of many options!

Dynamically Update Element Content after multiplying an integer input with a variable

I request some help with updating the result element content with the product of integer input in the text field with a pre-defined variable.
What i wanted to achieve is the content of the element with id="result" to be updated automatically, i want to achieve this using jquery:
Below is my code, thanks in advance.
<script>
function updateresult(){
var operand1 = parseFloat($('slide').val()) || 1;
var operand2 = 25;
var produt;
produt = operand1 * operand2;
$('#result').html(product);
}
</script>
<!DOCTYPE HTML>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<div id="text">
Write to change:<input id="slide" type="text" onchange="updateText()" />
</div>
<div >Total is: <span id="result"></span></div>
<br/>
</body>
</html>
You can use keyup event of textbox in jquery.
$("#slide").keyup(function(e){
var operand1 = parseFloat($(this).val()) || 1;
var operand2 = 25;
var result = operand1 * operand2;
$("#result").html(result);
});
Working Sample
There are a couple of things:
your function is named updateresult() but you call a different function: onchange="updateText()"
Instead of $('slide') you need to use an id-selector $('#slide')
you have a typo in product, you sometimes refer to it as poduct
The code below fixes all of that
function updateText(){
var operand1 = parseFloat($('#slide').val()) || 1;
var operand2 = 25;
var product;
product = operand1 * operand2;
$('#result').text(product);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="text">
Write to change:<input id="slide" type="text" onchange="updateText()">
</div>
<div >Total is: <span id="result"></span></div>
There is one more thing: The change event gets fired only when the element loses focus, you may want to add paste and keyup events by removing the onchange attribute and add the following to your javascript
$('#slide').on('change keyup paste',updateText);
And yet another thing: you're using <!DOCTYPE HTML> so this is html5. But there are no self-closing tags in html5, so instead of <tag /> you should just write <tag>

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