ASP.NET - Set onclick event using javascript dynamically

Asked By Anandh Ramanujam on 28-Dec-10 04:08 AM
Hi,

In my web page i have created a html table like this...

 

<table id="tblAttachments" width="100%" border="1" style="width:100%;border-collapse:collapse;" align="center" cellspacing="0">

 

<tr class="style7">

 

<th style="width: 70%">

 

Attachment</th>

 

<th style="width: 30%">

 

<asp:linkbutton forecolor="#7E7E7E" onclientclick="javascript:confirm('Are you sure want to delete all');"

 

id="lnkRemoveAll" postbackurl="javascript:;" text="Remove All" runat="server"></asp:linkbutton>

 

</th>

 

 

</tr>

 

<tr id="trNoRecords" align="center">

 

<td colspan="2" style="width: 100%">

 

-- No Files to Attach --</td>

 

</tr>

 

</table>

In my javascript, i have created a row and cells dynamically. i have created one anchor element to a cell.

i have to set onclick event to the anchor tag...

How could we do that. Can anybody help me in this regard.

The javascript function:

function AddAttachment()

{

var fileUpload=document.getElementById('<%=exceptionFileUpload.ClientID%>').value;

var fileUploadArray=fileUpload.split('\\');

if (fileUploadArray.length>1)

{

var tblAttach=document.getElementById('tblAttachments');

var rowNoRecord = document.getElementById('trNoRecords');

rowNoRecord.parentElement.removeChild(rowNoRecord);

var rowCount=tblAttach.rows.length;

var row = tblAttach.insertRow(rowCount);

var cell1 = row.insertCell(0);

cell1.innerHTML=fileUploadArray[fileUploadArray.length-1];

var cell2 = row.insertCell(1);

var element2 = document.createElement("a");

element2.setAttribute('href','#');

// Here is the requirement to set onclick event. This event should call a function called 'RemoveAttachment' with the parameter 'row' object.

// element2.onclick

element2.innerHTML="Remove";

cell2.appendChild(element2);

}

else

{

alert("No file to attach");

}

}

Reena Jain replied to Anandh Ramanujam on 28-Dec-10 04:15 AM
hi,

by using attributes of button you can set the click even on button like this

signIn.setAttribute("onclick","functionName(args)"); 
or
tnMyButton.Attributes.Add("onclick", "window.open('http://www.myimage.com'); return false;";

Hope this will help you
Vivek Jagga replied to Anandh Ramanujam on 28-Dec-10 04:25 AM
Anandh,

Use

element2.setAttribute('onclick','javascript:myfunction();');
Anandh Ramanujam replied to Reena Jain on 28-Dec-10 04:28 AM
the function is calling, but the parameter is not passed correctly. I couldnt get value from that...
Reena Jain replied to Anandh Ramanujam on 28-Dec-10 04:51 AM
hi,

you want to return the value for function or want to pass the value. explain in brief
Anandh Ramanujam replied to Reena Jain on 28-Dec-10 08:01 AM
I want to pass the object 'row' already defined in that javascript to to the called function.

ex: element.setAttribute('onclick','functionname(row))