Im using JQuery to check the file size and name from an html file input field. The input field is:
<div id="uploadFile_div">
<input name="source" id="imageFile" type="file" style ="border: 1px solid #576675;">
</div>
And the JQuery:
$(document).ready(function(){
$('#imageFile').bind('change', function() {
alert("Test");
//.... perform input checks...//
});
});
Now, I have a selection box, where the user choose between image file or video file, and based on it I send the file to different servers and also perform appropriate checks. In order to reset the input field (I do it when the user changes the selection box from Video to Image and vise versa) I use this JavaScript trick:
document.getElementById('uploadFile_div').innerHTML = document.getElementById('uploadFile_div').innerHTML;
But After 1 execution of this JavaScript, The JQuery isn’t binded and I don’t see the “Test” alert when I select files.
How can i rebind the JQuery ?
Thanks.
You could use a delegated event handler, binding the event to the parent div:
Demo: http://jsfiddle.net/SfgpS/
(If you’re using a version of jQuery older than 1.7 use
.delegate()instead of.on(). If you’re using a really old version of jQuery use.live().)When you rewrite the
.innerHTMLof the container that effectively erases the old input element including event handlers that were bound to it, and then creates a new input. So you could re-run your original.bind()statement at that point to bind a handler to the new input.With a delegated event handler as for that syntax of
.on()you bind the handler to the container, i.e., to the div in this case. Events that happen to the container’s child(ren) bubble up to the container (and then right on up to the document). So in this case when a change event reaches the div jQuery checks whether it originated with an element matching the selector from the second parameter of.on()and if so calls the your handler function. This lets you handle events on elements that don’t exist at the time you create the handler. It doesn’t matter if you remove and re-add the child elements because the handler was bound to the container.(Note that if you leave out that second parameter to
.on()it creates a non-delegated handler just the same as.bind().)