Schlaus
Schlaus

Reputation: 19252

Prevent clicking on file input's label from opening file browser

I have a form where users can upload images, and I'm using <label>s for each input. However, in this particular case it's not desirable for the file browser to open when a user clicks on the label element. I've tried using jQuery's preventDefault on the labels, but it doesn't work. Any way to disable this functionality? I'd still like to stick with labels instead of replacing them with other elements.

My HTML:

<div class="control-group">
    <label for="userImages" class="nodefault">Please upload images</label>
    <div class="controls">
        <input type="file" id="userImages" name="userImages" />
    </div>
<div>

and my JS:

$(document).ready(function() {
    $(".nodefault").click(function(e) {
        e.preventDefault();
    });
});

I'm using:
jQuery v1.10.1
jQueryUI v1.10.3
Twitter Bootstrap v2.3.2

Upvotes: 2

Views: 7575

Answers (2)

ready() not closed

$(document).ready(function () {
    $(".nodefault").click(function (e) {
        e.preventDefault();
    });
});

Upvotes: 2

Dhaval Marthak
Dhaval Marthak

Reputation: 17366

You have a Typo in .ready() missing ) in the end

$(document).ready(function() {
    $(".nodefault").click(function(e) {
        e.preventDefault();
    });
});

Works fine Here

Upvotes: 6

Related Questions