Ali_dotNet
Ali_dotNet

Reputation: 3279

adding onclick event to javascript dynamically created element

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

Upvotes: 6

Views: 23692

Answers (2)

Munter
Munter

Reputation: 1089

You should really use event delegation instead of setting an event handler on each node you create.

This way you can assign a single event handler to the table around the table rows, which handles all clicks on all rows and removes that row. You set it once only.

table.onclick = function (e) {
    var target = e.target || window.event.srcElement;

    while (target.nodeName !== 'TR') {
        target = target.parentNode;
    }
    target.parentNode.reamoveChild(target);
}

Upvotes: 2

RightSaidFred
RightSaidFred

Reputation: 11327

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;
    } 
};

Upvotes: 7

Related Questions