html input onchange doesn't accept anonymous function

15,371

Solution 1

onchange="(function(){alert('this should work')})()"

Solution 2

Its not a good practice to create inline functions.

I would suggest something like

<html>
 <script>
   function myFunction(){
     alert('hey it works');
   }
 </script>
 <body>
 <input type ='file' id='kmlFiles2' onchange="myFunction();" />
 </body>
 </html>

you can also consider writing

function init(){
   document.getElementById('kmlFiles2').onclick=function(){alert('this also works');};
}
window.onload=init;
Share:
15,371
dooderson
Author by

dooderson

Updated on June 22, 2022

Comments

  • dooderson
    dooderson almost 2 years

    Why does this not work?

     <input type="file" id="kmlFiles2" multiple onchange="function(){alert('why does this not work')}()">
    

    chrome gives me an error, Uncaught SyntaxError: Unexpected token (.

    Firefox tells me SyntaxError: function statement requires a name.

    But this does work?

     <input type="file" id="kmlFiles2" multiple onchange="alert('but this does work')">
    

    http://jsfiddle.net/ewzyV/

    I am asking because I was was trying to use and MVC framework that injects code into the onchange event.