Click here to Skip to main content
15,884,969 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am crating html Buttons dynamicaly(with id) on-client-click of another html-button(btAdd).
I need to call a javascript fuction onclick event of dynamically created html-button.
is it possible. my code is as follows
=========================

<input id="btnAdd" type="button" value="Add More HTML Button" style="width:75px" onclick="Addbtn()" />

XML
<div id ="uploadArea">

</div>



===========================================

JavaScript
function Addbtn() 
{
            if (!document.getElementById || !document.createElement)
                return false;

            var uploadArea = document.getElementById("uploadArea");
            if (!uploadArea) return;

            var newline = document.createElement("br");           
            uploadArea.appendChild(newline);          

           
            
            var newDeleteButton = document.createElement("input");            
            newDeleteButton.type="submit";
            newDeleteButton.size="5";
            newDeleteButton.value="Delete";          
            
            
            if (!newDeleteButton.lastAssignedId) 
            {
            newDeleteButton.lastAssignedId = 100;            
            }

            newDeleteButton.setAttribute("id", "btn"+ newDeleteButton.lastAssignedId);
            newDeleteButton.setAttribute("name", "btn" + newDeleteButton.lastAssignedId);           
            uploadArea.appendChild(newDeleteButton);

            newDeleteButton.lastAssignedId++            
            
} 



function Need_To_Call_This_fucntion_OnClick_of_DynamicallyCreatedHTML_Button
{
alert("ok");
}
Posted
Updated 2-Dec-11 21:00pm
v2

1 solution

Use addEventListener and/or attachEvent[^] to bind your function to the click event.
 
Share this answer
 
Comments
SHAJANCHERIAN 3-Dec-11 7:11am    
Hi,
I have added the the following line
newDeleteButton.addEventListener('click',alert("ok"),false);

But alert in is invoking when button is added. Need to alert when I click on the added button.
Graham Breach 3-Dec-11 7:52am    
If you do that, you are calling alert("ok") at the time that you add the button. You need to wrap the code you want to call when the button is clicked inside a function:


function clickedFunction()
{
alert("ok");
}

...

newDeleteButton.addEventListener('click',clickedFunction,false);

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900