Manju Manju -4 years ago 205
Javascript Question

Attach event to dynamic elements in javascript

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 event is not firing. Solution would be really appreciated.

Javascript code:

document.addEventListener('DOMContentLoaded', function () {
document.getElementById('btnSubmit').addEventListener('click', function () {
var name = document.getElementById('txtName').value;
var mobile = document.getElementById('txtMobile').value;
var html = '<ul>';
for (i = 0; i < 5; i++) {
html = html + '<li>' + name + i + '</li>';
html = html + '</ul>';

html = html + '<input type="button" value="prepend" id="btnPrepend" />';
document.getElementsByTagName('form')[0].insertAdjacentHTML('afterend', html);

document.getElementById('btnPrepend').addEventListener('click', function () {
var html = '<li>Prepending data</li>';
document.getElementsByTagName('ul')[0].insertAdjacentHTML('afterbegin', html);


HTML Code:

<div class="control">
<input id="txtName" name="txtName" type="text" />
<div class="control">
<input id="txtMobile" type="text" />
<div class="control">
<input id="btnSubmit" type="button" value="submit" />

Answer Source

This is due to that your element is dynamically created and you should event delegation to handle event.

    if( && 'brnPrepend'){//do something}

jquery make it easier:

 $(document).on('click','#btnPrepend',function(){//do something})

Here is an article you can read about event delegation event delegation article

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download