2018/02/05

How to add event listener to a dynamically created button using JavaScript.

This post is about how to add event listener to a dynamically created button using JavaScript.

The Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<!DOCTYPE html>
<html>
    <head>
    </head>
    
    <body>
        <form>
            <div class="control">
                <label>Name</label>
                <input id="txtName" name="txtName" type="text" />
            </div>
            <div class="control">
                <label>Mobile</label>
                <input id="txtMobile" type="text" />
            </div>
            <div class="control">
                <input id="btnSubmit" type="button" value="submit" />
            </div>
        </form>
        
        <script>
            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);
                    });
                });
            });
        </script>  
    </body>
</html>

The Result









No comments:

Post a Comment