2

I am trying to use an image as a file type button in my application, but on click of image the function is executing but button document.getElementById("myFile").click(); is not executing. Whats wrong with my code?

HTML:

  <div align="center">
      <a href="#" id="other-color" onClick='loadFile()'><img style="width:75px;height:auto" src="icons/slr-camera-2-256.png"/></a>
      <input type="file" id="myFile" style="display:none" />
    </div>

Script:

 function loadFile()
        {

            alert("test");
            document.getElementById("myFile").click();
        }
Rene Pot
  • 24,681
  • 7
  • 68
  • 92
Vinod
  • 2,263
  • 9
  • 55
  • 104

4 Answers4

1

You can try like this, using JQuery:

 <input type="file" id="FileInput" style="display: none"/>
 <img src="abc.png" id="UploadPic" style="cursor: pointer;" />

And JQuery:

<script type="text/javascript">
  $(document).ready(function(){
      $("#FileInput").change(function() {
      $("#UploadPic").click();
     });
  });
</script>
0

To stay on the safe side, separate your JS from your HTML. You're not the first to have problems with JS events imbedded in HTML. I find that this issue is best solved when both are separated.

Here is a version when they are seperate.

DEMO

HTML

<div align="center"> <a href="#" id="other-color"><img style="width:75px;height:auto" src="icons/slr-camera-2-256.png"/></a>

    <input type="file" id="myFile" style="display:none" />
</div>

JS

var a = document.getElementById('other-color');
a.onclick = loadFile;

function loadFile() {
    alert("test");
}
kemicofa ghost
  • 16,349
  • 8
  • 82
  • 131
0

Check this solution by (SpYk3HH) JsFiddle Or You can use the following:

$('#myFile').show();
$('#myFile').focus();
$('#myFile').click();
$('#myFile').hide();

The idea of Florin Mogos is to make them visible and focused before click event.

Community
  • 1
  • 1
MTM
  • 919
  • 10
  • 22
0

You can use trigger

HTML

<div align="center">
   <a href="javascript:void(0);" id="other-color"><img style="width:75px;height:auto" src="icons/slr-camera-2-256.png"/></a>
   <input type="file" id="myFile" style="display:none" />
</div>

jQuery

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $('#other-color').click(function(){
        $('#myFile').trigger('click');
    });
});
</script>
MH2K9
  • 11,951
  • 7
  • 32
  • 49