Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding onclick event to javascript dynamically created element

Tags:

javascript

I'm dynamically adding labels to my table when user selects combo box items, but also I want these dynamically added labels to be erasable when user clicks on them, here is my javascript function:

    function OnSelectedIndexChange()

{
    if (document.getElementById('cmbDestinationUser').selectedIndex != 0) {
        var spanTag = document.createElement("span");
        spanTag.id = "span1";
        var e = document.getElementById("cmbDestinationUser");
        var strUser = e.options[e.selectedIndex].text;
        spanTag.innerHTML = strUser;
        var TR = document.createElement('tr');
        var TD = document.createElement('td');
        TD.appendChild(spanTag);
        TR.appendChild(TD);
        document.getElementById('tblReceivers').appendChild(TR);
    }
    document.getElementById('cmbDestinationUser').selectedIndex = 0;
}

should I add onclick to spantag? how can I do so? should I create another function for erasing or can I define the remove operation in this function thanks

like image 298
Ali_dotNet Avatar asked Dec 09 '11 13:12

Ali_dotNet


People also ask

How do you add an event dynamic to an element?

Attaching the event dynamicallyclassName = 'dynamic-link'; // Class name li. innerHTML = dynamicValue; // Text inside $('#links'). appendChild(li); // Append it li. onclick = dynamicEvent; // Attach the event!

How can you adding new elements dynamically in JavaScript?

New elements can be dynamically created in JavaScript with the help of createElement() method. The attributes of the created element can be set using the setAttribute() method.

How do you dynamically assign an event listener to a button using JavaScript?

To attach event handlers to the dynamically created button, we need to select the button with a class of btn and add an event listener of click . We're saying that onclick of the button, the p tag with a class of moreInfo should display block .


1 Answers

Yes, add the onclick to the span:

spanTag.onclick = function() {
    this.innerHTML = '';
};

This just clears the content of the span. I wasn't sure exactly what you meant by "erasing".

If you wanted to remove the span entirely, do this:

spanTag.onclick = function() {
    this.parentNode.removeChild( this );
};

To remove the row, do this:

spanTag.onclick = function() {
    var el = this;
    while( (el = el.parentNode) && el.nodeName.toLowerCase() !== 'tr' );

    if( el )
        el.parentNode.removeChild( el );
};

Or to make it a little clearer perhaps:

spanTag.onclick = function() {
    var el = this.parentNode;
    while( el ) {
       if( el.nodeName.toLowerCase() === 'tr' ) {
           el.parentNode.removeChild( el );
           break;
       }
       el = el.parentNode;
    } 
};
like image 90
RightSaidFred Avatar answered Nov 14 '22 22:11

RightSaidFred