2

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

Schlaus
  • 18,144
  • 10
  • 36
  • 64
  • 1
    Typo in `.ready()` missing `)` in the end – Dhaval Marthak Jul 26 '13 at 15:56
  • That is browser functionality. If you have a label for a file input the browser automatically does the same as clicking on the input field itself. You don't have to do anything to get that behaviour. – Jim Martens Jul 26 '13 at 16:01
  • @roasted Yes, he wants to **prevent** that default behaviour. If you want to prevent it, you have to do something. – Jim Martens Jul 26 '13 at 16:03
  • @roasted that's because I don't want to prevent the default function from all labels, just file upload ones. – Schlaus Jul 26 '13 at 16:04
  • While removing the `for` attribute would work, it's not an ideal situation for accessibility reasons. – DaveMongoose Jul 26 '13 at 16:04
  • Ok my bad, for attribute works and e.preventDefault() do the trick... – A. Wolff Jul 26 '13 at 16:07
  • So OP, now you have edited your typos, is it working or not? – A. Wolff Jul 26 '13 at 16:09
  • It is, but in the end it wasn't a typo (the code here is just the essential parts of much much more code), but actually a weird caching problem I hadn't run into before. The code was working, but my test browsers didn't have the latest version of the JS. – Schlaus Jul 26 '13 at 16:11

2 Answers2

6

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

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

Works fine Here

Dhaval Marthak
  • 17,246
  • 6
  • 46
  • 68
  • Hmm, so it does. That typo doesn't exist in the actual code, so I guess it wasn't a simple mistake in logic, but an error somewhere else. Thanks! – Schlaus Jul 26 '13 at 16:01
2

ready() not closed

$(document).ready(function () {
    $(".nodefault").click(function (e) {
        e.preventDefault();
    });
});
Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107