...

View Full Version : adding a value to a text input while using getElementById



Ludwig2012
07-04-2012, 07:49 PM
All i am tryinh to do is add 123 to the value nombre and displaying that result in resultat. Any help would be appreciated :)

<body>

<form action="#" method="post">
<input type="text" id="nombre">
<input type="text" id="resultat">
<input type="button" onclick="calculus()" value="Calculate"/>
</form>


<script type ="text/javascript">
function calculus()
{
var addnumber=document.getElementById("nombre");
var total= addnumber + 123;
resultat.value= "total";
}

</script>

</body>

Philip M
07-04-2012, 08:33 PM
I am unclear whether you want to add the numeric value 123 to the number input by the user, or concatenate the string value 123. I am assuming that you want to add the number, so that if the user enters 2 the result is 125.



<form action="#" method="post">
<input type="text" id="nombre">
<input type="text" id="resultat" readonly>
<input type="button" onclick="calculus()" value="Calculate"/>
</form>


<script type ="text/javascript">
function calculus() { // prefer to place the opening brace on the same line, not the following line
var addnumber=Number(document.getElementById("nombre").value); // form values are strings unless converted to numbers
var total= addnumber + 123; // + will add numbers, concatenate strings
document.getElementById("resultat").value= total; // you must use document.getElementById()
}

</script>


document.getElementById("resultat").value= "total"; would place the literal word total in the textbox.


I heard him then, for I had just
Completed my design
To keep the Menai Bridge from rust
By boiling it in wine.
- Lewis Carroll

Ludwig2012
07-04-2012, 10:34 PM
Yes i want to add 123 to the users number. If someone putts in 2 well the result will be 2+123= 125

felgall
07-04-2012, 11:20 PM
Yes i want to add 123 to the users number. If someone putts in 2 well the result will be 2+123= 125

The code Philip provided does exactly what you want then.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum