Adding Number by javascript - javascript

<html>
<head>
<title>JavaScript - using function</title>
<script>
function add(){
var value1=document.getElementById("n1").value;
var value2=document.getElementById("n2").value;
document.getElementById("result").value=parseFloat(value1)+parseFloat(value2);
}
</script>
</head>
<body>
<label>First Number:<input type="number" id="n1"/></label>
<label>Second Number:<input type="number" id="n2"/></label>
<input type="button" value="Add" onClick="add()" />
<p>
Result = <span id="result" ></span>
</p>
</body>
</html>
I am new to JavaScript and wanted to create a script that add numbers up. After pressing "Add" button, I cannot get the result to be displayed. How to get the result displayed?

Two things wrong here...
1)
<input type="button" value="Add" /> change it to
<input type="button" value="Add" onclick="add()" />
Also,
2)
document.getElementById("result").value=parseFloat(value1)+parseFloat(value2);
to
document.getElementById("result").innerHTML=parseFloat(value1)+parseFloat(value2);
PS : This is not a assignment solving website :P

First, You Should Change
document.getElementById("result").value = value1 + value2
To This:
document.getElementById("result").innerHTML = n1 + n2
Because value stands for the attribute value for < input >, not the text written
in the tag.
Second, Change The Button Code To:
<input type="button"value="Add"onclick="add()">
This "onclick" is something called event in javascript,
It means at clicking on the button "Add" it performs the funtion called "add()".
If You Are New To Javascript You Will Know Everything.
Just Be Patient.

It worked with the following changes
-> calling add function with onclick event
-> using innerhtml in place of value
<html>
<head>
<title>JavaScript - using function</title>
<script>
function add(){
var value1=document.getElementById("n1").value;
var value2=document.getElementById("n2").value;
console.log(value1,value2)
document.getElementById("result").innerHTML=parseFloat(value1)+parseFloat(value2);
}
</script>
</head>
<body>
<label>First Number:<input type="number" id="n1"/></label>
<label>Second Number:<input type="number" id="n2"/></label>
<input type="button" value="Add" onclick="add()"/>
<p>
Result = <span id="result" ></span>
</p>
</body>
</html>
Hope this helps

Its better to put the js at the end of the document - also as noted the onclick handler needs to call the function. I also tidied up the code a little.
<html>
<head>
<title>JavaScript - using function</title>
<style>label{display:block}</style>
</head>
<body>
<label>First Number:<input type="number" id="n1"/></label>
<label>Second Number:<input type="number" id="n2"/></label>
<input type="button" value="Add" onclick="add()">
<p>Result = <span id="result" ></span></p>
<script>
function add(){
var value1=parseFloat(document.getElementById("n1").value);
var value2=parseFloat(document.getElementById("n2").value);
var total= value1 + value2;
document.getElementById("result").innerText=total;
}
</script>
</body>
</html>

Related

My results of calculation appear on a different page

I need to create code which automatticaly calculates the circumference when the length and width are entered in two different boxes.
I managed to do so, but I want the answer to appear underneath the "calculate" button, but the answer will make the button and boxes disappear. Could someone tell me what I need to change?
Here is my code:
<!DOCTYPE html>
<html>
<body>
<form>
Width:<br>
<input id="Width" type="text" name="Width">
<br>Length<br>
<input id="Length" type="text" name="Length">
<br><br>
<input type="button" value="Calculate circumference" onclick="doMath()">
</form>
<script>
function doMath() {
var Width1 = document.getElementById('Width').value;
var Length1 = document.getElementById('Length').value;
var Circ = parseInt(Width1) + parseInt(Width1) + parseInt(Length1) + parseInt(Length1);
document.write(Circ);
}
</script>
</body>
</html>
Do not use document.write function. The write() method is mostly used for testing: If it is used after an HTML document is fully loaded, it will delete all existing HTML. Create a paragraph tag and give an id and place your result in that paragraph.
<!DOCTYPE html>
<html>
<body>
<form>
Width:<br>
<input id="Width" type="text" name="Width">
<br>Length<br>
<input id="Length" type="text" name="Length">
<br><br>
<input type="button" value="Calculate circumference" onclick="doMath()">
<p id="result">
</p>
</form>
<script>
function doMath() {
var Width1 = document.getElementById('Width').value;
var Length1 = document.getElementById('Length').value;
var Circ = parseInt(Width1) + parseInt(Width1) + parseInt(Length1) + parseInt(Length1);
//document.write(Circ);
document.getElementById("result").textContent = Circ;
}
</script>
</body>
</html>
Try adding a black paragraph to the html and then use document.getElementById("").innerHTML to change the text inside of it.

Form with input and output immediately reload the page after printing the output

I need to do a simple homework where you enter two integers in two text fields of a form and then you compute the sum and you print it in a "text field (not editable)". My program seems to work but it prints the right output and immediately reload the page. I want the page to remain with the printed output if the user does not click again on "submit" button
Here is my code HTML & JS :
function updateExpr() {
var x1 = document.getElementById("n1").value;
var x2 = document.getElementById("n2").value;
var sum = +x1 + +x2;
document.getElementById("sum").innerHTML = +x1 + +x2;
}
<!DOCTYPE html>
<html>
<head>
<title>Number in a form</title>
<link href="mystyle.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="function.js">
</script>
</head>
<body>
<div id="mainDiv">
<H3>Insert two positive numbers</H3>
<form>
First number:<br>
<input id="n1" type="text" name="firstname"><br>
Second number:<br>
<input id="n2" type="text" name="lastname">
<BR>
<input type="submit" value="Submit" onClick="updateExpr()"/><BR><BR>
</form>
The sum is:<br>
<output id="sum" name="x" for="a b"></output>
</div>
<noscript>
Sorry: Your browser does not support or has disabled javascript
</noscript>
</body>
</html>
When form is submited, the page will be reloaded. To prevent this you should change input type attribute from submit to button.
<input type="submit" value="Submit" onClick="updateExpr()"/>
to
<input type="button" value="Submit" onClick="updateExpr()"/>
You can simply avoid server call by changing your form tag
<form onSubmit="return false">
You dont really need a form to do something like this.
Forms send values to the backend, e.g. a server.
You only want to manipulate some front-end elements like a container to have some new text inside it.
a <form> tag typically sends you to some URI with some aprameters,
this is done by the actions attribute.
<form action="addnames.php">
for example would call the addnames.php script on your server...
You dont need a server tho..look below:
function updateExpr() {
var x1 = document.getElementById("n1").value;
var x2 = document.getElementById("n2").value;
var sum =x1 +x2;
document.getElementById("sum").innerHTML = sum;
}
<h2>HTML Forms</h2>
First name:<br>
<input id="n1" type="text" name="firstname" value="Mickey">
<br>
Last name:<br>
<input id="n2" type="text" name="lastname" value="Mouse">
<br><br>
<button type="submit" onclick="updateExpr()">Submit</button>
<div id="sum">
</div>
<script>
</script>
I would recommand you to add onSubmit method to the form instead of onclick to the input.
Also you better add a return : false to your function and add onsubmit="return updateExpr()".
function updateExpr() {
var x1 = document.getElementById("n1").value;
var x2 = document.getElementById("n2").value;
var sum = +x1 + +x2;
document.getElementById("sum").innerHTML = +x1 + +x2;
return false;
}
<!DOCTYPE html>
<html>
<head>
<title>Number in a form</title>
<link href="mystyle.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="function.js">
</script>
</head>
<body>
<div id="mainDiv">
<H3>Insert two positive numbers</H3>
<form onsubmit="return updateExpr()">
First number:<br>
<input id="n1" type="text" name="firstname"><br>
Second number:<br>
<input id="n2" type="text" name="lastname">
<BR>
<input type="submit" value="Submit" onClick="updateExpr()"/><BR><BR>
</form>
The sum is:<br>
<output id="sum" name="x" for="a b"></output>
</div>
<noscript>
Sorry: Your browser does not support or has disabled javascript
</noscript>
</body>
Another way of doing this would have been to add a button outside of the form linked to the function by onclick event
juste add preventDefault(), like this
function updateExpr(e) {
e.preventDefault();
var x1 = document.getElementById("n1").value;
var x2 = document.getElementById("n2").value;
var sum = +x1 + +x2;
document.getElementById("sum").innerHTML = +x1 + +x2;
}

Output in a textbox in a webpage

I'm trying to input 2 parameters and output it an another TEXTBOX.
This is my code:
<!DOCTYPE html>
<html>
<head>
<script src="proj4js/lib/proj4js/lib/proj4js-compressed.js"></script>
</head>
<body>
<script>
function func1 (x,y){
var z=x+y
document.getElementById("Z").innerHTML = z;
}
</script>
<form >
first input:<br>
<input id="Y" type="text" y="Y" value=85>
<br>
second input:<br>
<input id="X" type="text" x="X" value=15>
<br>
The Answer:<br>
<input id="Z" type="text" z="Z" >
<br><br>
</form>
<button type="button" onclick="func1(parseInt(document.getElementById('X').value),parseInt(document.getElementById('Y').value))">Try it</button>
What is wrong here? I tried this to show the result as simple paragraph and I succeed, but I need to display it in a textbox.
Replace this:-
document.getElementById("Z").innerHTML = z;
with
document.getElementById("Z").value = z;
An <input> element uses value and not innerHTML:
document.getElementById("Z").value = z;

Show a javascript variable on html textbox

All I have to do is to show a number in a textbox and a button which add 10 every time I press it, here's my code (it doesn't work).
<head>
<script type="text/javascript">
var n=parseInt(ocument.forms["formNum"]["numero"].value);
document.getElementById("numero").value=n;
function sumar() {
n=document.forms["formNum"]["numero"].value+10;
document.forms["formNum"]["numero"].value=n;
}
function inicializar() {
n=document.forms["formNum"]["numero"].value=0;
}
</script>
</head>
<body>
<form name="formNum">
<p>
<input type="text" size="10" name="numero" id="numero" />
</p>
<p>
<input type="button" name="sumar" value="Sumar" onclick="sumar()" />
<input type="button" name="inicializar" value="Iniciar a 0" onclick="inicializar()" />
</p>
</form>
</body>
<body>
<script type="text/javascript">
function sumar(){
document.getElementById("numero").value = parseInt(document.getElementById("numero").value)+10;
}
function inicializar(){
document.getElementById("numero").value=0;
}
</script>
<form name="formNum">
<p>
<input type="text" size="10" name="numero" id="numero" value="0" />
</p>
<p>
<input type="button" value="Sumar" onclick="sumar()" />
<input type="button" value="Iniciar a 0" onclick="inicializar()" />
</p>
</form>
</body>
Five suggestions.
It is always better to give unique ids to your html elements.
Never name your HTML elements and javascript functions the same.
If you want to access the html element from javascript, if you know the id, use getElementById.
Use Firebug or Developer tools from the browser, to debug.
If you want to access your elements with the hierarchy, use elements in the form like this document.forms["formNum"].elements["numero"].value. Check this example
Demo: http://jsfiddle.net/DPJCR/
This code should work:
<input type="text" id="mytext">
<script type="text/javascript">
var elem = document.getElementById("mytext");
elem.value = "My default value";
</script>
See: Set the value of an input field
Maybe you are getting an exception from the parseInt that prevents the value from changing.
If it is an option to use jQuery, try this:
function sumar(){
$("#numero").attr("value", parseInt($("#numero").attr("value"), 10)+10);
}
Try this this will help you
var count=10;
$('#btnSumar').click(function(){
if($('#numero').val()=='')
{
$('#numero').val(count);
}else
$('#numero').val(eval($('#numero').val())+count);
});
$('#btnInc').click(function(){
$('#numero').val('');});
Fiddle here

Create a "calculation form" in javascript

so I have a project now, as an addition to my company's website, we want to show our clients how much they can save on gas by buying one of our electric cars, I'm responsible for making it happen, I don't know how to approach this using javascript, can you guys give me a hand? our marketing guy got the idea from this website, that is basically what we want, but I was hoping i could make it a little better on some aspects:
1st-the client wouldn't have to press submit to see the results, as they fill the last field, the calculated part is populated automatically, for this i've been fiddling with the onChange event, unsuccessfully though xD
here's what I have so far, it is not working, at least on dreamweaver's live mode, haven't tested it online yet as I was hoping to develop the whole thing offline:
<script type="text/javascript">
function calc(){
var km=document.getElementById(km).value;
var euro=document.getElementById(euro).value;
var consumo=document.getElementById(consumo).value;
var cem_km=consumo*euro;
var fossil_day=(cem_km*km)/100;
return fossil_day;
}
</script>
<form name="calc" id="calc" >
<p>
Km/dia
<input type="text" name="km" id="km" value="" />
</p>
<p>
€/Litro
<input type="text" name="euro" id="euro" value="" />
</p>
<p>
Litros/100km
<input type="text" onChange="calc()" name="consumo" id="consumo" value="" />
</p>
<input type="button" onClick="calc()" name="submit" id="submit" value="Calcular" />
<script type="text/javascript">
var fossil_day = calc();
document.write('<p>'+fossil_day+'</p>');
</script>
</form>
Please note that although I have this already, I wouldnt mind not doing this at all and using another solution, even if it doesnt use forms, I'm just showing what i have already so you can tell me how I'm wrong and how I can have a better approach at it
there are many errors inside your code
document.getElementById() needs the element id in brackets ''
you can't create a element with the same name,id as a function calc else it will throw an error as it's an object and not a function.
your executing the function onload... but you want it to be executed when the button is clicked & onchange.
you don't need to add value if empty and name if you use getElementById
return false in the function on buttons inside form else it could send the form and so refresh the page.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>calc</title>
<script>
function calc(){
var km=document.getElementById('km').value;
var euro=document.getElementById('euro').value;
var consumo=document.getElementById('consumo').value;
var cem_km=consumo*euro;
var fossil_day=(cem_km*km)/100;
document.getElementById('result').innerHTML=fossil_day;
return false
}
</script>
</head>
<body>
<form>
<p>Km/dia<input type="text" id="km"/></p>
<p>€/Litro<input type="text" id="euro" /></p>
<p>Litros/100km<input type="text" onChange="calc()" id="consumo" /></p>
<input type="button" onClick="calc()" value="Calcular" />
</form>
<div id="result"></div>
</body>
</html>
Useing jQuery (and html5 type="number" form fields):
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form>
<p>
Km/dia
<input type="number" name="km" id="km" value="" />
</p>
<p>
€/Litro
<input type="number" name="euro" id="euro" value="" />
</p>
<p>
Litros/100km
<input type="number" name="consumo" id="consumo" value="" />
</p>
<div id="fossil-day"></div>
</form>
<script src="http://codeorigin.jquery.com/jquery-1.10.2.min.js"></script>
<script>
function calculate(){
var km = $('#km').val();
var euro = $('#euro').val();
var consumo = $('#consumo').val();
var cem_km = consumo*euro;
var fossil_day = (cem_km*km)/100;
$('#fossil-day').html(fossil_day);
}
$(function() {
/*when #consumo input loses focus, as per original question*/
$('#consumo').blur(function(){
calculate();
});
});
</script>
</body>
</html>

Categories