Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add onclick event programmatically

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?

like image 399
nidhi Avatar asked Nov 05 '12 09:11

nidhi


People also ask

Can we use onclick in JavaScript?

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.

Why we use onclick in JavaScript?

The onclick event in JavaScript lets you as a programmer execute a function when an element is clicked.

Does Onclick only work on buttons?

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.

Is Onclick a callback?

The addEventListener() and onclick both listen for an event. Both can execute a callback function when a button is clicked.


2 Answers

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);
  }
}
like image 177
mike Avatar answered Oct 09 '22 08:10

mike


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

like image 16
Dan Dascalescu Avatar answered Oct 09 '22 07:10

Dan Dascalescu