Reputation: 452
In this simple program, the script does not write result id="result"
just flashes the resultant value. Can anybody take a look and show why this behavior? What am I doing wrong?
function multiplication() {
var product,
no1 = document.getElementById('no1').value,
no2 = document.getElementById('no2').value;
product = no1 * no2;
document.getElementById("result").innerHTML = product;
}
function division() {
var divis,
no1 = document.getElementById('no1').value,
no2 = document.getElementById('no2').value;
divis = no1 / no2;
document.getElementById("result").innerHTML = divis;
}
<h2>Write a JavaScript program to calculate multiplication and division of two numbers ?</h2>
<h3>Sample Form</h3>
<form name="sample" method="POST">
1st Number:
<input type="text" id="no1" name="firstno" /> 2nd Number:
<input type="text" id="no2" name="secondno" />
<button id="mul" onclick="multiplication();">Multiply</button>
<button id="div" onclick="division();">Division</button>
</form>
<p id="result"></p>
Upvotes: 2
Views: 1168
Reputation: 353
<form name="sample" method="POST">
1st Number:
<input type="text" id="no1" name="firstno" /> 2nd Number:
<input type="text" id="no2" name="secondno" />
<button id="mul" type="button" onclick="multiplication();">Multiply</button>
<button id="div" type="button" onclick="division();">Division</button>
function multiplication(event) {
var product,
no1 = document.getElementById('no1').value,
no2 = document.getElementById('no2').value;
product = no1 * no2;
document.getElementById("result").innerHTML = product;
}
function division(event) {
var divis,
no1 = document.getElementById('no1').value,
no2 = document.getElementById('no2').value;
divis = no1 / no2;
document.getElementById("result").innerHTML = divis;
}
Upvotes: -1
Reputation: 11
<h2>Write a JavaScript program to calculate multiplication and division of two numbers ?</h2>
<h3>Sample Form</h3>
<form name="sample" method="POST">
1st Number:
<input type="text" id="no1" name="firstno" /> 2nd Number:
<input type="text" id="no2" name="secondno" />
</form>
<button id="mul" onclick="multiplication();">Multiply</button>
<button id="div" onclick="division();">Division</button>
<p id="result"></p>
Put the button
tag outside the form
tag.
Upvotes: 1
Reputation: 819
<button type="button" id="mul" onclick="multiplication();">Multiply</button>
<button type="button" id="div" onclick="division();">Division</button>
This might help you.
Upvotes: 0
Reputation: 28409
Your JS is working but when the user clicks a submit button the form is also submitted, because that's the default action.
Prevent the form from submitting.
<form onsubmit="event.preventDefault();" name="sample" method="POST">
Upvotes: 2
Reputation: 943645
The new page doesn't have the DOM changes that were on the old page.
Either prevent the default behaviour of the submit button or bind your event handler to a different kind of control.
Upvotes: 2