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
Attaching the event dynamicallyclassName = 'dynamic-link'; // Class name li. innerHTML = dynamicValue; // Text inside $('#links'). appendChild(li); // Append it li. onclick = dynamicEvent; // Attach the event!
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.
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 .
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;
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With