I\'m trying to insert html data dynamically to a list that is dynamically created, but when i try to attach an onclick event for the button that is dynamically created the e
You must attach the event after insert elements, like that you don't attach a global event on your document
but a specific event on the inserted elements.
e.g.
document.getElementById('form').addEventListener('submit', function(e) {
e.preventDefault();
var name = document.getElementById('txtName').value;
var idElement = 'btnPrepend';
var html = `
<ul>
<li>${name}</li>
</ul>
<input type="button" value="prepend" id="${idElement}" />
`;
/* Insert the html into your DOM */
insertHTML('form', html);
/* Add an event listener after insert html */
addEvent(idElement);
});
const insertHTML = (tag = 'form', html, position = 'afterend', index = 0) => {
document.getElementsByTagName(tag)[index].insertAdjacentHTML(position, html);
}
const addEvent = (id, event = 'click') => {
document.getElementById(id).addEventListener(event, function() {
insertHTML('ul', '<li>Prepending data</li>', 'afterbegin')
});
}
<form id="form">
<div>
<label for="txtName">Name</label>
<input id="txtName" name="txtName" type="text" />
</div>
<input type="submit" value="submit" />
</form>
You can do something similar to this:
// Get the parent to attatch the element into
var parent = document.getElementsByTagName("ul")[0];
// Create element with random id
var element = document.createElement("li");
element.id = "li-"+Math.floor(Math.random()*9999);
// Add event listener
element.addEventListener("click", EVENT_FN);
// Add to parent
parent.appendChild(element);
I know that the topic is too old but I gave myself some minutes to create a very useful code that works fine and very easy using pure JAVASCRIPT
.
Here is the code with a simple example:
String.prototype.addEventListener=function(eventHandler, functionToDo){
let selector=this;
document.body.addEventListener(eventHandler, function(e){
e=(e||window.event);
e.preventDefault();
const path=e.path;
path.forEach(function(elem){
const selectorsArray=document.querySelectorAll(selector);
selectorsArray.forEach(function(slt){
if(slt==elem){
if(typeof functionToDo=="function") functionToDo(el=slt, e=e);
}
});
});
});
}
// And here is how we can use it actually !
"input[type='number']".addEventListener("click", function(element, e){
console.log( e ); // Console log the value of the current number input
});
<input type="number" value="25">
<br>
<input type="number" value="15">
<br><br>
<button onclick="addDynamicInput()">Add a Dynamic Input</button>
<script type="text/javascript">
function addDynamicInput(){
const inpt=document.createElement("input");
inpt.type="number";
inpt.value=Math.floor(Math.random()*30+1);
document.body.prepend(inpt);
}
</script>
This is due to the fact that your element is dynamically created. You should use event delegation to handle the event.
document.addEventListener('click',function(e){
if(e.target && e.target.id== 'brnPrepend'){
//do something
}
});
jquery makes it easier:
$(document).on('click','#btnPrepend',function(){//do something})
Here is an article about event delegation event delegation article