fmz fmz - 2 years ago 102
HTML Question

Using an html button to call a javascript function

I am trying to use an html button to call a javascript function.

Here's the code:

<input type="button" value="Capacity Chart" onclick="CapacityChart();">

It doesn't seem to work correctly though. Is there a better way to do this?

Here is the link: click on the capacity tab in the bottom left section. The button should generate an alert if the values are not changed and should produce a chart if you enter values.

Answer Source

There are a few ways to handle events with HTML/DOM. There's no real right or wrong way but different ways are useful in different situations.

1: There's defining it in the HTML:

<input id="clickMe" type="button" value="clickme" onclick="doFunction();" />

2: There's adding it to the DOM property for the event in Javascript:

//- Using a function pointer:
document.getElementById("clickMe").onclick = doFunction;

//- Using and anonymous function:
document.getElementById("clickMe").onclick = function () { alert('hello!'); };

3: And there's attaching a function to the event handler using Javascript:

var el = document.getElementById("clickMe");
if (el.addEventListener)
    el.addEventListener("click", doFunction, false);
else if (el.attachEvent)
    el.attachEvent('onclick', doFunction);

Both the second and third methods allow for inline/anonymous functions and both must be declared after the element has been parsed from the document. The first method isn't valid XHTML because the onclick attribute isn't in the XHTML specification.

The 1st and 2nd methods are mutually exclusive, meaning using one (the 2nd) will override the other (the 1st). The 3rd method will allow you to attach as many functions as you like to the same event handler, even if the 1st or 2nd method has been used too.

Most likely, the problem lies somewhere in your CapacityChart() function. After visiting your link and running your script, the CapacityChart() function runs and the two popups are opened (one is closed as per the script). Where you have the following line:


Try the following instead:"text/html");

When I saw your code I thought you were writing it specifically for IE. As others have mentioned you will need to replace references to document.all with document.getElementById. However, you will still have the task of fixing the script after this so I would recommend getting it working in at least IE first as any mistakes you make changing the code to work cross browser could cause even more confusion. Once it's working in IE it will be easier to tell if it's working in other browsers whilst you're updating the code.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download