So I have some basic code in html here, i just have two textbox which u can type numbers in and when you click the button, it adds em both up, and in a perfect world, it would display the answer in that third textbox.
<html>
<head>
</head>
<script type="text/javascript">
function myfunction()
{
var first = document.getElementById("textbox1").value;
var second = document.getElementById("textbox2").value;
var answer = +first + +second;
var textbox3 = answer;
}
</script>
<body>
<input type="text" name="textbox1" id="textbox1" />
+
<input type="text" name="textbox2" id="textbox2" />
<input type="submit" name="button" id="button1" onclick="myfunction()" value="=" />
<input type="text" name="textbox3" id="textbox3" readonly="true"/>
<br />
Your answer is: --
</body>
</html>
however, i can't get the answer to display in that textbox3. Does anyone know how to assign a value to that third textbox from a variable?
also, as an added bonus, if anyone knows a way to also make the last line "Your answer is: --" display the answer as well, that would be amazing.
This question is related to
javascript
html
textbox
You're on the right track with using document.getElementById()
as you have done for your first two text boxes. Use something like document.getElementById("textbox3")
to retrieve the element. Then you can just set its value property: document.getElementById("textbox3").value = answer;
For the "Your answer is: --", I'd recommend wrapping the "--" in a <span/>
(e.g. <span id="answerDisplay">--</span>
). Then use document.getElementById("answerDisplay").textContent = answer;
to display it.
Even if this is already answered (1 year ago) you could also let the fields be calculated automatically.
The HTML
<tr>
<td><input type="text" value="" ></td>
<td><input type="text" class="class_name" placeholder="bla bla"/></td>
</tr>
<tr>
<td><input type="text" value="" ></td>
<td><input type="text" class="class_name" placeholder="bla bla."/></td>
</tr>
The script
$(document).ready(function(){
$(".class_name").each(function(){
$(this).keyup(function(){
calculateSum()
;})
;})
;}
);
function calculateSum(){
var sum=0;
$(".class_name").each(function(){
if(!isNaN(this.value) && this.value.length!=0){
sum+=parseFloat(this.value);
}
else if(isNaN(this.value)) {
alert("Maybe an alert if they type , instead of .");
}
}
);
$("#sum").html(sum.toFixed(2));
}
Source: Stackoverflow.com