The file replacement function input type = "file" works, but it requests the file twice

Using jQuery Mobile 1.7.1 to replace the native input type="file" button.

The code works, but makes a second request to the search / open file bit.

What am I missing?

Same behavior in Chrome and FF (not tried elsewhere).

 <div id="fileInputButton" data-role="button" data-icon="gear" style="width:150px;margin:0 auto; text-align:center">Import</div> <div id="filename"></div> <input style="opacity:0;" id="the_real_file_input" name="foobar" type="file"> <script> $('#fileInputButton').click(function() { $('#the_real_file_input').click(); }); $('input[type=file]').bind('change', function() { var str = ""; str = $(this).val(); $("#filename").text(str); }).change(); </script> 

Thank you for your help!

UPDATE: works fine in this http://jsfiddle.net/pg3Qf/ script until JQuery Mobile is applied. (Thanks @wirey!)

FINAL UPDATE: This fixes the double trigger problem:

 $('#fileInputButton').click(function(e) { e.stopImmediatePropagation(); $('#the_real_file_input').click(); }); 

And this fixes the "C: \ fakepath" issue in Chrome and Safari:

 str = $(this).val().replace(/C:\\fakepath\\/i, ''); 
+4
source share
1 answer

I don't know why, but using stopImmediatePropagation stops it from starting twice. It's not like the event will bubble up to anything

 $('#fileInputButton').click(function(e) { e.stopImmediatePropagation(); console.log('triggered'); $('#the_real_file_input').click(); }); 

http://jsfiddle.net/pg3Qf/3/

+8
source

All Articles