Reputation: 9
What did I do wrong?
HTML
<form name="Calc">
<BR>
<input type="text" name="1" size="20">*
<input type="text" name="2" size="20">=
<input type="text" name="sum" size="20">
<BR>
<input type="button" name="Calc" value="Calculate" onClick="calcsum()">
</form>
Script
function calcsum() {
sum.value = 1.value * 2.value;
}
Upvotes: 0
Views: 177
Reputation: 147523
If you pass a reference to the button in the listener:
<input type="button" ... onclick="calcsum(this)">
Then in the function you can use it to get a reference to the form and its other controls by name:
function calcsum(button) {
var form = button.form;
sum.value = form['1'].value * form['2'].value;
}
Note that form control values are always strings, so be careful with using +
for addition.
I'm not a fan of mixed case for HTML attribute names. They are not case sensitive, but their related DOM properties are. So better to use "onclick" for the attribute to match the DOM "onclick" property.
Upvotes: 0
Reputation: 12213
You should use document.getElementsByName
Try:
function calcsum() {
document.getElementsByName("sum")[0].value = document.getElementsByName("1")[0].value * document.getElementsByName("2")[0].value;
}
Upvotes: 3