Skip to content
Advertisement

The default action of a file input disappears while parent div return false

I have a parent div which contains an input element, and every time the parent div is clicked, it returns false.

<div class="media-asset">
    <input  type="file" name="picture-label" >
</div>
$('body').on({
        click:function(){
            return false;
        }
},'.media-asset');

The problem is when the parent div returns false, the default action of a file input is gone, and it won’t prompt the user to upload a file. Is it possible to manually trigger the default action of a file input?

$('body').on({
            click:function(){
                //manually trigger the file input
                return false;
            }
    },'.media-asset input');

The reason I let the parent div to return false is when the user click outside of the parent div, it would hide the parent div, and while the user click inside of the parent div, it would not hide itself.

Advertisement

Answer

No need to manually trigger it. Specify event.stopPropagation() on the '.media-asset input' click event and remove the return false from that as well:

event.stopPropagation()

Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

event.stopPropagation() – jQuery API Documentation

$('body').on({
  click:function(){
    return false;
  }
},'.media-asset');

$('body').on({
  click:function(event){
    event.stopPropagation();
  }
},'.media-asset input');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="media-asset">
    <input  type="file" name="picture-label" >
</div>
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement