Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function to replace file input type="file" button works but asks for file twice

Using jQuery Mobile 1.7.1 for a button replacement of native input type="file".

Code works but forces a second request on the browse/open file bit.

What am I missing?

Same behavior on Chrome and FF (have 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>

Thanks for your help!

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

FINAL UPDATE: This fixes the double trigger issue:

$('#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, '');
like image 401
user1452893 Avatar asked Feb 20 '23 16:02

user1452893


1 Answers

I don't know why but using stopImmediatePropagation stops it from triggering twice. It doesn't look like the event would be bubbling up to anything

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

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

like image 121
wirey00 Avatar answered May 01 '23 17:05

wirey00