Click here to Skip to main content
15,891,704 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi friends

i have button on each click button i will create a label dynamically,with same ids
,now how can i write a onclick event for the each dynamically created label ,


Thanks in advance
Posted
Comments
Dennis Baberich 12-Jan-15 8:17am    
Pure javascript or jquery? Also, different elements should not have the same id.
ZurdoDev 12-Jan-15 8:49am    
have you googled how to attach an event to an object using JS? Many examples online.

1 solution

I would strongly recommend using jQuery, but then you should better use if for inserting the new label as well, to get a already jQuery-wrapped object. Please see:
http://api.jquery.com/category/manipulation/dom-insertion-around/[^],
http://api.jquery.com/category/manipulation/dom-insertion-inside/[^],
http://api.jquery.com/category/manipulation/dom-insertion-outside/[^].

Then the click event is written like this:
JavaScript
myLabel.click(function() {
    // some handler code here
    // by the way:
    var sender = $(this); // the jQuery wrapper of the sender object
                          // in your case the same label you clicked on
    // this way, you can use sender's properties in your handler
});

Please see: http://api.jquery.com/click[^].

If you need to learn jQuery (highly recommended), please see:
http://en.wikipedia.org/wiki/JQuery[^],
http://jquery.com[^],
http://learn.jquery.com[^],
http://learn.jquery.com/using-jquery-core[^],
http://learn.jquery.com/about-jquery/how-jquery-works[^] (start from here).

If you don't want to listen to a good advice and want to write it in Javascript by yourself from scratch, you can always add a handler by using
JavaScript
document.getElementById("myLabel").addEventListener("click", function(){ alert("Hello World!"); });

The sample above is a combination of samples shown here: http://www.w3schools.com/js/js_htmldom_eventlistener.asp[^].

—SA
 
Share this answer
 
v5
Comments
CPallini 12-Jan-15 15:36pm    
5.
Sergey Alexandrovich Kryukov 12-Jan-15 15:38pm    
Thank you, Carlo.
—SA

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