4

Sorry if you find this question repetitive, but I looked around, tried, failed, so need your help.

one.html

 <html>
    <head>
    <link rel="stylesheet" href="one.css" >
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script src="one.js"></script>
    </head>
    <body>
       <div class='some-class' id="add-image">
            <input type="file" id="myfile" style="display:none" />
            <h4> I want to open the file upload dilogue when anywhere of this div has been clicked</h4>
       </div>
   </body>
 </html>

one.css

.some-class{
border: 1px solid grey;
}

h4{
    text-align:center;
}

one.js

$("#add-image").click(function(){
  $("input[id='myfile']").click();
});

It shows sometimes

event.returnValue is deprecated. Please use the standard event.preventDefault() instead.

sometimes

uncaught rangeerror maximum call stack size exceeded

I don't know whats happening, if its a issue with the jquery version? Can you please help me? A working code sample or maybe a jsfiddle? Thank you in advance :)

the.big.lebowski
  • 259
  • 1
  • 3
  • 12

3 Answers3

3

You need to add the click handler within a dom ready handler because when one.js is executed the add-image element is not present in the dom structure

jQuery(function ($) {
    $("#add-image").click(function () {
        $("#myfile").click();
    });
})

Dom Ready

Since the file input element is within the myfile element triggering the click element on the file element will cause a recursive error saying callstack exceeded

The solution is to move the file element out of the myfile element

<input type="file" id="myfile" style="display:none" />
<div class='some-class' id="add-image">
     <h4> I want to open the file upload dilogue when anywhere of this div has been clicked</h4>
</div>

Demo: Fiddle

Arun P Johny
  • 365,836
  • 60
  • 503
  • 504
1

I thin kyou have missed the dom ready handler.
try this:

$(document).ready(function(){
  $("#add-image").click(function(){
     $("#myfile").trigger('click');
  });
});
Alessandro Minoccheri
  • 32,975
  • 19
  • 110
  • 159
  • event.returnValue is deprecated. Please use the standard event.preventDefault() instead. Uncaught RangeError: Maximum call stack size exceeded – the.big.lebowski Nov 27 '13 at 15:27
1

change your html to

     <div class='some-class' id="add-image">
        <h4> I want to open the file upload dilogue when anywhere of this div has been clicked</h4>
    </div>
    <input type="file" id="myfile" style="display:none" />
rajesh kakawat
  • 10,330
  • 1
  • 18
  • 38