The problem is that inline handlers have a very peculiar scope chain. They're surrounded inside two with
s: one for the document, and one for the element on which the inline handler exists. For example, with
<button id="button" onclick="<<CODE HERE>>">
When clicked, the effect will be similar to as if the following was executed:
with (document) {
with (button) {
<<CODE HERE>>
}
}
When you reference click
inside one of these handlers, it will first try to find a click
property on the element, and it finds one: it refers to HTMLButtonElement.prototype.click
:
<form>
<label>Length of the triangle: </label><br>
<input id="l" type="text" placeholder="Length"><br>
<label>Base of the triangle</label><br>
<input id="b" type="text" placeholder="Base"><br>
</form>
<p id=area></p>
<button
id="button"
onclick="console.log(click === button.click, click === HTMLButtonElement.prototype.click)"
>Click:</button>
As a result, clicking the button results in HTMLButton.prototype.click
being called on that button, which, here, does nothing, which is why you're not seeing any results, and not even an error message.
Either use a different variable name:
function handleClick() {
var l = document.getElementById('l');
var b = document.getElementById('b');
var a = document.getElementById('area');
var area = l.value * b.value;
a.innerHTML = "The ans is " + area;
}
<form>
<label>Length of the triangle: </label><br>
<input id="l" type="text" placeholder="Length"><br>
<label>Base of the triangle</label><br>
<input id="b" type="text" placeholder="Base"><br>
</form>
<p id=area></p>
<button onclick="handleClick()"
>Click:</button>
Or, even better, avoid inline handlers entirely, since they behave so weirdly - attach the listener properly using Javascript instead. Using addEventListener
also lets you avoid global variable pollution, which is inelegant and can lead to bugs and messy code.
document.querySelector('button').addEventListener('click', () => {
var l = document.getElementById('l');
var b = document.getElementById('b');
var a = document.getElementById('area');
var area = l.value * b.value;
a.textContent = "The ans is " + area;
});
<form>
<label>Length of the triangle: </label><br>
<input id="l" type="text" placeholder="Length"><br>
<label>Base of the triangle</label><br>
<input id="b" type="text" placeholder="Base"><br>
</form>
<p id=area></p>
<button>Click:</button>