Search code examples
javascripthtmlprototypejs

Event.observe() not working; ProtoytypeJS library


I have this code.

<html>
    <head>
        <script src="//ajax.googleapis.com/ajax/libs/prototype/1.7.1.0/prototype.js">    </script>
        <script>
            Event.observe('clickme', 'click', function(event) {
                alert('clicked');
            });

            Event.observe('uploadme', 'change', function(event) {
                alert('hola');
            });

        </script>
    </head>
    <body>
        <form enctype="multipart/form-data" action="insertimage.php" method="post" name="changer">
            <input name="MAX_FILE_SIZE" value="10240000" type="hidden">
            <input id="uploadme"  type="file">
            <input type="button"  id="clickme" value="Upload Stuff!" />
            <input id="sub" type="submit" />
        </form>
    </body>
</html>

This is not working. I am unable to get alert for anything. Can anyone please suggest a solution?


Solution

  • Try adding the script just above body closing tag, like:

    </head>
    <body>
    <form enctype="multipart/form-data" action="insertimage.php" method="post" name="changer">
    <input name="MAX_FILE_SIZE" value="10240000" type="hidden">
    <input id="uploadme"  type="file">
    <input type="button"  id="clickme" value="Upload Stuff!" />
    <input id="sub" type="submit" />
    </form>
    <script>
    Event.observe('clickme', 'click', function(event) {
        alert('clicked');
    });
    Event.observe('uploadme', 'change', function(event) {
        alert('hola');
    });
    </script>
    </body>
    

    Demo: jsFiddle

    Or, if you want to keep the script tag inside head,other option would be:

    Event.observe(window, 'load', function() {
        Event.observe('clickme', 'click', function(event) {
            alert('clicked');
        });
        Event.observe('uploadme', 'change', function(event) {
            alert('hola');
        });
    });