Search code examples
javascriptinputonchangecreation

Programmatic creation of text input with JavaScript


I am currently learning JavaScript, and I got stuck at the following problems: I have tried to dynamically create an input of type text from JavaScript and to set its onChange method, but it is fired only when the page is loaded. In addition, document.onload does not work for creating my input, but window.onload does, although the tutorials I read claim that these two are almost the same thing. The code is the following:

<html>
    <head>
        <script type="text/javascript">
            function f(value) {
                alert(value);
                return true;
            }

            window.onload = function() {
                if (document.getElementById("cloned") == null) {
                     var clonedInput = document.createElement('input');
                     clonedInput.type = 'text';
                     clonedInput.value = "";
                     clonedInput.id = 'cloned';
                     clonedInput.size = 20;
                     clonedInput.onChange = f(clonedInput.value);
                     var lastChild = document.getElementById("parent");
                     document.body.insertBefore(clonedInput, lastChild);
                }
            };
        </script>
    </head>
    <body>
        <input id="toClone" type="text"/>
        <div id="parent"></div>
    </body>
</html>

Solution

  • f(clonedInput.value) calls the function immediately and sets its return value (which is true in this case) as event handler.

    You want to use an anonymous function:

    clonedInput.onchange = function(){ f(this.value); };
    

    Note: While HTML attributes are case-insensitive, JavaScript object properties are not.