Dziamid
Dziamid

Reputation: 11579

Allow default action for target event and prevent default action for parent

We have this kind of markup:

<a href="#">
   <input type="file" />
</a>

By default when you click on input "Select file" window appears and location changes to "#". How do I prevent browser from changing location?

What I have tried:

//location still changes
$('input').bind('click', function (e) {
  e.stopPropagation();
});

//prevents "Select file" window
$('input').bind('click', function (e) {
  e.preventDefault();
});

//prevents "Select file" window 
$('a').bind('click', function (e) {
  e.preventDefault();
});

Upvotes: 1

Views: 1856

Answers (2)

L105
L105

Reputation: 5419

You need to check if the user has clicked on the a element and not the input file. This should work.

$('a').click(function(e) {
    if ($(e.target).is('a')) {
        e.preventDefault();
    }
});

DEMO

Upvotes: 0

Anton
Anton

Reputation: 32581

Try changing $(e) to e.

e.preventDefault();

When doing $(e).preventDefault() causes error

Uncaught TypeError: Object [object Object] has no method 'preventDefault' 

Upvotes: 1

Related Questions