Javascript Form How to - Create input element and add click event handler








Question

We would like to know how to create input element and add click event handler.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
<!--from ww w. j  a v a2 s.  c o  m-->
    document.body.innerHTML += '<input type="image" id="alertMeID" style="position:fixed;top:10px;left:0" //src="http://www.java2s.com/style/download.png" ///>';
    document.body.innerHTML += '<input type="image" id="alertMeID2" style="position:fixed;top:100px;left:100px" //src="http://www.java2s.com/style/download.png" />';
    document.getElementById('alertMeID').addEventListener('click', function() {
        do_this("some text")
    }, false);
    document.getElementById('alertMeID2').addEventListener('click', function() {
        do_this("another text")
    }, false);
    function do_this(sendingParameter) {
        document.body.appendChild(document.createTextNode(sendingParameter));
    }

</script>
</head>
<body>
</body>
</html>

The code above is rendered as follows: