gal007
gal007

Reputation: 7182

Not working handler on "onchange" event

I'm trying to make some changes in DOM after an image is selected with an "input file" HTML5 element. So, I added a handler to the "onchange" event, but it is not working!

<span class="btn-file" >
    Load and show alert 
    <input type="file" onchange="performSomeActions()"/>
</span>

And supose this is the function:

function performSomeActions(){
    alert("lalala");
}

The error I get when I execute the code and after choosing a file is:

Uncaught ReferenceError: performSomeActions is not defined 

I thought maybe I was wrong with the event name, but if you replace the input definition with the following line, it is working!

<input type="file" onchange="alert('alo');"/>

THE FIDDLE: http://jsfiddle.net/pvhaggrv/5/

Thanks in advance!

Upvotes: 0

Views: 3852

Answers (4)

Gildas.Tambo
Gildas.Tambo

Reputation: 22643

DEMO

HTML:

<span class="btn-file" >
    Load and show alert 
    <input type="file" id="input">
</span>

<br/>
<img id="img"> </img>

SCRIPT:

function handleFiles() {
    alert("lol");
  var fileList = this.files; /* now you can work with the file list */
}
var inputElement = document.getElementById("input");
inputElement.addEventListener("change", handleFiles, false);

SOURCE:

Dynamically adding a change listener

Upvotes: 1

Luizgrs
Luizgrs

Reputation: 4873

Your fiddle doesn't work because fiddle executes all your javascript in the a anonymous function:

//<![CDATA[ 
window.onload=function(){
function performSomeActions(){
    alert("yyy");
}

}//]]>  

So your function isn't in the global scope and your HTML can't see it.

To your code works you need to include your function directly at the HEAD, you can do this in fiddle changing the checkbox at the left side: http://jsfiddle.net/pvhaggrv/12/

HOWEVER, you should not add event listeners this way, you should use addEventListener like kougiland said in his answer.

Upvotes: 1

Mukund Kumar
Mukund Kumar

Reputation: 23181

just put javascript function in body tag just before ending of body tag like this

<span class="btn-file" >
    Load and show alert 
    <input type="file" id="file" onchange="performSomeActions();"/>

</span>
<br/>
<img id="img"> </img>
<script>
     var performSomeActions=function(){
    alert("yyy");
}
</script>

see fiddle

Upvotes: 1

Birgit Martinelle
Birgit Martinelle

Reputation: 1889

JSFiddle doesn't like calls to javascript embedded in your html. In the interest of keeping your code clean event handlers are assigned via javascript instead. Change your html to:

<input type="file" id='fileInput'/>

and then in your JS

document.getElementById('fileInput').onchange = function() {
    performSomeActions();
}

working fiddle: http://jsfiddle.net/bmartinelle/rhbphvhu/

Upvotes: 1

Related Questions