views:

86

answers:

2
<html>
<body>
    <script language="javascript">
    document.getElementById('myfileId').onchange = function(e) { alert('change'); }
    </script>

    <form action="" >
        <input type="file"  id="myfileId" name="myfile">
    </form>

    </body>
</html>

How can I call the JavaScript function after a file selection.

Edit: 1

<html>
<body>

    <form>
        <input type="file"  id="myfileId" name="myfile">
    </form>
 <script language="javascript">
  window.onload = function() 
        { 
    alert("Test");

    document.getElementById('myfileId').onblur =  function(e) { alert('change'); }
        }
    </script>
    </body>
</html>
+8  A: 

You have to put that <script> after the <input>. The document.getElementById('myfileId') does not exist if you put it before, so it will return nothing.

KennyTM
@coderex: How it's not working?
KennyTM
@coderex: Not reproducible. Hint: You need to close (confirm) the file choosing dialog to see the alert.
KennyTM
Change events tend to fire when focus is lost, not as soon as a change is made.
David Dorward
@KennyTM the onchange is not wrking any morreee
coderex
@KennyTM check my edit section I added my latest code. you can check and let me know whats wrong
coderex
@coderex: Still works. Note that with `onblur` you need to click outside of the `<input>` to fire.
KennyTM
@KennyTM how can i trigger a JavaScript function, after file selection. ? Any option for that. ?
coderex
+2  A: 

As @Kenny says, you have to either put the script after the input declaration so the element actually exists when the script is executed, or alternatively, add the function to the document's onload event:

window.onload = function() 
        { document.getElementById('myfileId').onchange =  
          function(e) { alert('change'); }
        }
Pekka