Button function call does not work? - javascript

I want a webpage that has something like this:
Welcome
[textbox] [textbox] [Multiply!]
Enter a value to multiply.
represented by this html code:
window.onload = function begin() {
document.getElementById("demo").innerHTML = "Welcome";
}
function multiply(var1, var2) {
document.getElementById('multiply').innerHTML = var1 * var2
}
<body onload="onload();">
<p id='demo'> </p>
<form>
<input type='number' name=num1>
<input type='number' name=num2>
<button onclick=multiply(num1, num2)> Multiply! </button>
</form>
<p id='multiply'> Enter a value to multiply. </p>
</body>

You lack " in onclick, and I changed the script. I also removed unnecessary elements. Just add them back in your codes
EDIT
I returned the <form> tag and added the type="button" attribute to prevent the form from submitting. Thanks to #Patrick Roberts and #Nick Tirrell for the information
function multiply() {
var num1 = document.getElementById("num1").value;
var num2 = document.getElementById("num2").value;
document.getElementById('multiply').innerHTML = num1 * num2
}
<form>
<input id="num1" type='number'>
<input id="num2" type='number'>
<button type="button" onclick="multiply()"> Multiply! </button>
<p id='multiply'> Enter a value to multiply. </p>
</form>

give each input an id attribute then use that to get the value(s) to multiply, e.g. document.getElementById("my-id-1").value. Also, use a basic
doc.getElementById("my-button").addEventListener('click', function(evt) {
//do your thing.
});

<!DOCTYPE html>
<html>
<head>
<title> Test </title>
</head>
<body>
<form>
<input type='number' id='num1'>
<input type='number' id='num2'>
<button type='button' onclick="multiply()"> Multiply! </button>
</form>
<p id='multiply'> Enter a value to multiply. </p>
<script src="01_using_javascript.js"> </script>
</body>
</html>
function multiply() {
var numberOne = document.getElementById('num1').value;
var numberTwo = document.getElementById('num2').value;
var multiply = document.getElementById('multiply');
var multipliedResult = numberOne * numberTwo;
multiply.innerHTML = multipliedResult;
}

Related

Why isn't my code adding a number with the input field (HTML/Javascript - Beginner)?

for practice as a beginner I am trying to take a number from a text field, have the user press a button that adds 2 to that number, and then displays it through HTML. However, for some reason I keep getting NaN when applying the code below.
//Setup
var num1 = document.querySelector(".input-box").value;
var btn = document.querySelector(".btn");
//Add
var sum = parseInt(num1) + 2;
btn.addEventListener('click', (e) => {
e.preventDefault();
document.querySelector("#output").innerHTML = sum;
})
<html>
<head>
<title>Calculate</title>
<style>
</style>
</head>
<body>
<div class="sign">
<h1>Calculate</h1>
<form>
<input type="text" class="input-box" placeholder="Enter Number">
<input class="btn" type="button" value="Add 2">
</form>
<h1 id="output"></h1>
</div>
<script src="manip3.js"></script>
</body>
</html>
You need to move the num1 and sum the inside the event listener
//Setup
var btn = document.querySelector(".btn");
//Add
btn.addEventListener('click', (e) => {
e.preventDefault();
// get the number
var num1 = document.querySelector(".input-box").value;
// add 2
var sum = parseInt(num1) + 2;
document.querySelector("#output").innerHTML = sum;
})
<html>
<head>
<title>Calculate</title>
<style>
</style>
</head>
<body>
<div class="sign">
<h1>Calculate</h1>
<form>
<input type="text" class="input-box" placeholder="Enter Number">
<input class="btn" type="button" value="Add 2">
</form>
<h1 id="output"></h1>
</div>
<script src="manip3.js"></script>
</body>
</html>
You need to calculate the sum inside the click function. Right now it is calculating before the butten is clicked, when the page loads, which means the input is empty.
as mentioned above you need to resolve after the button is clicked. you could change your variables to function variables.
//Setup
var num1 = function() {return document.querySelector(".input-box").value};
var btn = document.querySelector(".btn");
//Add
var sum = function() {return parseInt(num1()) + 2};
btn.addEventListener('click', (e) => {
e.preventDefault();
document.querySelector("#output").innerHTML = sum();
})
make the input type = number for better validation
make the button type = submit cause this is form and you need to submit
add submit event to the form cause you can't prevent default without submit event
select input inside the event and convert its value to number by adding + before it
// select from
var form = document.getElementById("form");
form.addEventListener('submit', (e) => {
e.preventDefault();
// select input and convert its value to number
var num1 = +document.querySelector(".input-box").value;
document.querySelector("#output").innerHTML = num1 + 2;
// wipe out form after submit
form.reset();
});
<div class="sign">
<h1>Calculate</h1>
<form id="form">
<input type="number" class="input-box" placeholder="Enter Number">
<input class="btn" type="submit" value="Add 2">
</form>
<h1 id="output"></h1>
</div>

I am trying to convert Fahrenheit to Celsius but it's not working what am i doing wrong? - Javascript (needs to have a form and a clear button)

<html>
<head>
<title>
Form
</title>
</head>
<body>
<script type="text/javascript">
function calculate (form)
{
cel = fah * 0.5555 - 32;
document.getElementById("finish").innerHTML = cel;
}
</script>
<form name="myform" action="" method="get"> Turn Fahrenheit to Celsius! <br>
<input type="number" name="fah">
<input type="button" name="button" value="calculate" onClick="calculate(this.form)">
<button type="reset" value="Reset">Reset</button>
</form>
<p id="finish">°C</p>
</body>
</html>
Edit1: Moved the inner.HTML into the Function
So the reset button is the only thing that works. Is it possible to calculate the math this way?
You asked a question on how to create a pizza form a while ago and you deleted it soon as it was down voted a few times.
The point to note here is, it is okay if a few people dislike your question. You've joined StackExchange not to gain points but to learn a few things. Your question could be helpful to a lot of others out there in this world. So here it is the answer to your pizza question
<html>
<body>
<p>A pizza is 13 dollars with no toppings.</p>
<form action="form_action.asp">
<input type="checkbox" name="pizza" value="Pepperoni" id="pep">Pepperoni + 5$<br>
<input type="checkbox" name="pizza" value="Cheese" id="che">Cheese + 4$<br>
<br>
<input type="button" onclick="myFunction()" value="Send order">
<input type="button" onclick="cost()" value="Get cost">
<br><br>
<input type="text" id="order" size="50">
</form>
<script>
function myFunction() {
var pizza = document.forms[0];
var txt = "";
var i;
for (i = 0; i < pizza.length; i++) {
if (pizza[i].checked) {
txt = txt + pizza[i].value + " ";
}
}
document.getElementById("order").value = "You ordered a pizza with: " + txt;
}
function cost() {
var pep = 5;
var che = 4;
var pizza = 13;
var total = 0;
if (document.getElementById("pep").checked === true) {
total += pep;
}
if (document.getElementById("che").checked === true) {
total += che;
}
document.getElementById("order").value = "The cost is : " + total;
}
</script>
</body>
</html>
Thanks. I hope this helps you.
Adeno Fixed it by declaring what fah was. you can also see your errors with f12.
https://stackoverflow.com/users/965051/adeneo
<html>
<head>
<title>
Form
</title>
</head>
<body>
<script type="text/javascript">
function calculate(form) {
var cel = (document.getElementById("fah").value -32) * 5 / 9;
document.getElementById("finish").innerHTML = cel;
}
</script>
<form name="myform" action="" method="get"> Turn Fahrenheit to Celsius!
<br>
<input type="number" name="fah" id="fah">
<input type="button" name="button" value="calculate" onClick="calculate(this.form)">
<button type="reset" value="Reset">Reset</button>
</form>
<p id="finish">°C</p>
</body>
You never get the value from the input type = "number"
Try this
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script>
function calculate()
{
var fah = document.getElementById('fah').value;
var cel = parseFloat(fah * 0.5555 - 32);
document.getElementById("finish").innerHTML = cel;
}
</script>
</head>
<body>
<form>
Turn Fahrenheit to Celsius! <br>
<input type="text" name="fah" id="fah">
<input type="button" name="button" value="calculate" onClick="calculate()">
<button type="reset" value="Reset">Reset</button>
</form>
<p id="finish">°C</p>
</body>
</html>
Couple things: You need to set the innerhtml from within the function because the variable is in the function. Or you could have declared the variable outside the function first like var fah = "" then the function. But since you declared it in the function only the function can see it. So i moved the innerhtml set into the function.
Also, javascript likes to use id's not name = "fah" You can call an element by name but id is easier.
i rounded it to integer. you would get 9 decimals your way.
Lastly, innerhtml set clears all the html so you would lose the °C the way you had it.
<html>
<head>
<title>
Form
</title>
</head>
<body>
<script type="text/javascript">
function calculate (form)
{
var fah = this.fah.value;
cel = Math.round((fah-32) / 1.8);
document.getElementById("finish").innerHTML = cel+"°C";
}
</script>
<form name="myform" action="" method="get"> Turn Fahrenheit to Celsius! <br>
<input type="number" name="fah" id = "fah">
<input type="button" name="button" value="calculate" onClick="calculate(this.form)">
<button type="reset" value="Reset">Reset</button>
</form>
<p id="finish"></p>
</body>
</html>

how to increment and decrement the text box value using javascript?

i am trying increment and decrement a number if user is giving in text box is 15 it should be incremented when click a button and also decrement when button clicking...
this is my javascript code
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function incNumber() {
for(i=1;i>0;i++){
document.getElementById("display").value=i;
}
}
function decNumber() {
for(i=1;i>0;i--){
document.getElementById("display").value=i;
}
}
</script>
</head>
<body>
<form>
<input type="text" value="0"/>
<input type="button" value="Increase" id="inc" onclick="incNumber()"/>
<input type="button" value="Decrease" id="dec" onclick="decNumber()"/>
<label id="display"></label>
</form>
</body>
</html>
Use parseInt() function to convert the value from string to integer.
function incNumber(){
var c = parseInt(document.getElementsByTagName("input")[0].value);
c++;
document.getElementsByTagName("input")[0].value = c;
document.getElementById("display").innerHTML = c;
}
The logic stands for decNumber()
function decNumber(){
var c = parseInt(document.getElementsByTagName("input")[0].value);
c--;
document.getElementsByTagName("input")[0].value = c;
document.getElementById("display").innerHTML = c;
}
Few suggestions
1.Never mix up your markup with javascript. Consider attaching events click/change at javascript end
DOM search is costly.use it cautiously
3.Use parseInt(variablename,10) ->to convert it into integer
check the following snippet
window.onload=function(){
var incButton=document.getElementById("inc");
incButton.addEventListener("click",incNumber);
var decButton=document.getElementById("dec");
decButton.addEventListener("click",decNumber);
}
function incNumber() {
var displayValue= document.getElementById("display");
var text=document.getElementById("input");
var value=parseInt(text.value,10);
if(value==15){
displayValue.innerHTML=value+1;
}
}
function decNumber() {
var displayValue= document.getElementById("display");
var text=document.getElementById("input");
var value=parseInt(text.value,10);
displayValue.innerHTML=value-1;
}
<form>
<input type="text" value="0" id="input"/>
<input type="button" value="Increase" id="inc" />
<input type="button" value="Decrease" id="dec" />
<label id="display"></label>
</form>
Hope this helps
If you want to increment the label value by the input value try this
function incNumber(){
var num=0;
if(isNaN(document.getElementById('diplay').innerHTML)){
num=$("#inputVal").val();
}
else{
num=parseInt(document.getElementById('diplay').innerHTML)+$("#inputVal").val();
}
document.getElementById('diplay').innerHTML=num;
}
function decNumber(){
var num=0;
if(isNaN(document.getElementById('diplay').innerHTML)){
num=$("#inputVal").val();
}
else{
num=parseInt(document.getElementById('diplay').innerHTML)-$("#inputVal").val();
}
document.getElementById('diplay').innerHTML=num;
}
In HTML
<form>
<input type="number" id="inputVal" value="0"/>
<input type="button" value="Increase" id="inc" onclick="incNumber()"/>
<input type="button" value="Decrease" id="dec" onclick="decNumber()"/>
<label id="display"></label>
or you can define input type as number
<input type="number" id="numbrfield"/>
you will automatically get buttons to increment or decrement when you hover on the field.

How to set paragraph to textbox text

Let us say I have an HTML form, with two textboxes, I want to add the two numbers in the two textboxes and display the result in a paragraph. How can I do that?
Change paragraph according to textbox is what I can't find!
Very simple:
document.getElementById('sum').onsubmit = add;
function add(e) {
e.preventDefault();
var num1 = document.getElementById('num1').value;
var num2 = document.getElementById('num2').value;
var result = 'Result: ' + String(parseInt(num1) + parseInt(num2));
var p = document.getElementById('result');
p.innerHTML = result;
}
<form id="sum">
<label for="num1">First number:</label>
<br />
<input type="text" id="num1" />
<br />
<label for="num1">Second number:</label>
<br />
<input type="text" id="num2" />
<br />
<input type="submit" value="Add" />
</form>
<p id="result">Result:</p>
In the html we have a form with 3 inputs, 2 are type text and one is type submit. and also a paragraph.
In the javascript we assign to the form's onsumbit event the function add(), in the function we prevent the default so the form wont refresh the page, then we get the 2 values that were inputed, create a string that would contain the sum of those values and set the paragraph's innerHTML to it.
Create a calculator function and then you can fire it on keyup or you can assign it to a button if you'd like.
function calcTotal(){
var inputs = document.getElementsByTagName('input'),
result = 0;
for(var i=0;i<inputs.length;i++){
if(parseInt(inputs[i].value))
result += parseInt(inputs[i].value);
}
document.getElementById('total').innerHTML = 'Total: ' + result;
}
<form>
<input onkeyup="calcTotal()" type="text" />
<input onkeyup="calcTotal()" type="text" />
</form>
<p id="total"></p>
follow bellow JS code:
<html>
<head>
<title>Sum Two Number</title>
<script language="javascript">
function addNumbers()
{
var val1 = parseInt(document.getElementById("value1").value);
var val2 = parseInt(document.getElementById("value2").value);
if(val1 !== "" && val2 !== "") {
var result = val1 + val2;
document.getElementById('result').innerHTML = result;
}
}
</script>
</head>
<body>
value1 = <input type="text" id="value1" name="value1" value="0" onkeyup="javascript:addNumbers()"/>
value2 = <input type="text" id="value2" name="value2" value="0" onkeyup="javascript:addNumbers()"/>
<p>Answer = <span id="result"></span></p>
</body>
</html>
In this example, you have a form with 2 input. When you press on a button, the value of those 2 input is added inside a paragraph.
Hope this help.
function addInputContentToParagraph() {
var txtValue1 = document.getElementById('textbox1').value;
var txtValue2 = document.getElementById('textbox2').value;
document.getElementById('para').innerHTML = txtValue1 + ' ' + txtValue2;
}
a {
cursor:pointer;
border:1px solid #333;
padding:4px;
margin:10px;
display:inline-block;
}
<form id="myForm" name="myForm">
<input type="text" name="textbox1" id="textbox1" value="1">
<input type="text" name="textbox2" id="textbox2" value="2">
</form>
<a onclick="addInputContentToParagraph();">Add Input Values to Paragraph</a>
<p id="para"></p>

How do I tie html inputs into my javascript function?

<!DOCTYPE html>
<html>
<body>
<form>
Birth Year:<br>
<input type="number" name="birthYear">
<br>
Current Year:<br>
<input type="number" name="currentYear">
</form>
<button onclick="calculateAge()">Calculate Age</button>
<div id="output"></div>
<script>
function calculateAge(ghF, xhF) {
var ghF = "birthYear"
var xhF = "currentYear"
return (xhF - ghF);
} {
document.getElementByID("output").innerHTML = text;
};
</script>
</body>
When I click on the button it should print out "You are x age". Where would I add that text? At the moment nothing happens when I click on the button.
getElementById will return the DOM element having id as mentioned argument. .value is property of input element which will give the value of input
Instead of returning value, you must set the innerHTML/innerText after doing subtraction.
Note: You must assign unique id attributes to the element to retrieve DOM element.
function calculateAge() {
var ghF = document.getElementById("birthYear").value;
var xhF = document.getElementById("currentYear").value;
document.getElementById("output").innerHTML = xhF - ghF;
}
<form>
Birth Year:
<br>
<input type="number" name="birthYear" id="birthYear">
<br>Current Year:
<br>
<input type="number" name="currentYear" id="currentYear">
</form>
<button onclick="calculateAge()">Calculate Age</button>
<div id="output"></div>
function calculateAge() {
var ghF = document.getElementById("birthYear").value;
var xhF = document.getElementById("currentYear").value;
document.getElementById("output").innerHTML="You are " +(xhF - ghF) + " age";
}
EXAMPLE
The function is badly formed.
This will do the trick:
function calculateAge() {
var ghF = document.querySelector('[name="birthYear"]').value;
var xhF = document.querySelector('[name="currentYear"]').value;
document.getElementById("output").innerHTML = "You are "+(xhF - ghF)+" age";
}
<form>
Birth Year:
<br>
<input type="number" name="birthYear">
<br>
Current Year:
<br>
<input type="number" name="currentYear">
</form>
<button onclick="calculateAge()">Calculate Age</button>
<div id="output"></div>

Categories