How do I add an onclick
event to a tag in HTML programmatically?
I want to be able to click a link, and have an onclick
event attached to a Javascript function take effect on another tag.
Here is what I have so far:
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "text";
element1.id="List["+num+"].id";
element1.name="List["+num+"].id";
element1.onclick="javascript:CalCal()";
cell1.appendChild(element1);
I want to call a Javascript function CalCal()
on onClick
event. Is this possible?
The onclick event generally occurs when the user clicks on an element. It allows the programmer to execute a JavaScript's function when an element gets clicked. This event can be used for validating a form, warning messages and many more. Using JavaScript, this event can be dynamically added to any element.
The onclick event in JavaScript lets you as a programmer execute a function when an element is clicked.
onclick is not exclusive to buttons. You can also use onclick in plain JavaScript. Here is an example of a JavaScript onclick method: var item = document.
The addEventListener() and onclick both listen for an event. Both can execute a callback function when a button is clicked.
But keep in mind that addEventListener
is supported in IE just from version 9. To support older versions of IE you could use something like that:
if (element1.addEventListener) { // all browsers except IE before version 9
element1.addEventListener("click", CalCal, false);
} else {
if (element1.attachEvent) { // IE before version 9
element1.attachEvent("click", CalCal);
}
}
Yes you can add an onclick event programmatically in javascript like this:
element1 = document.getElementById("your_tag_id");
element1.addEventListener("click", CalCal)
This attaches an onClick event to tags with id="your_tag_id".
You can also remove the onclick event like this:
element1.removeAttribute("click");
More at https://developer.mozilla.org/en-US/docs/DOM/element.addEventListener
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With