-1

I've got a few buttons with the class PhotoUploadSubmit, and when a button is clicked, a custom click handler is used to look at sibling elements, etc. The click handler doesn't work, debugger never goes off, breakpoints are not hit, and I'm totally baffled.

<div class="formDataContext">
    <input type="file" name="ImageData" style="display:none" />
    <button class="PhotoUploadSubmit"><i class="fa fa-camera fa-5x"></i></button>
</div>

<script type="text/javascript">

$(function () {
    $(".PhotoUploadSubmit").on("click", function () {
        debugger;
        var currentFormDataContext = $(this).closest(".formDataContext");
        console.log(currentFormDataContext);
        var FileInput = currentFormDataContext.find("input:file")[0];
        console.log(FileInput);
        $(FileInput).click();
    });

    $("input:file").change(function () {
        var currentFormDataContext = $(this).closest(".formDataContext");
        uploadImage(currentFormDataContext);
    });
});

</script>

In terms of what I've tried, I've tried putting the click handler outside of document.ready, I've tried using the debugger; keyword, and I've tried setting breakpoints. There's no console errors.

alex
  • 6,818
  • 9
  • 52
  • 103

1 Answers1

3

Since the buttons are dynamically added so you can delegate. Example:

$("body").on("click", '.PhotoUploadSubmit', function () {
    debugger;
    var currentFormDataContext = $(this).closest(".formDataContext");
    console.log(currentFormDataContext);
    var FileInput = currentFormDataContext.find("input:file")[0];
    console.log(FileInput);
    $(FileInput).click();
});
MH2K9
  • 11,951
  • 7
  • 32
  • 49
  • Using this solved the problem. I wasn't considering that the buttons were dynamically rendered. I didn't think it would make a difference because the click handlers fired after `document.ready`! – alex Dec 08 '14 at 17:14
  • 1
    Some more explanations about delegates and especially event bubbling mechanism would have been cool. "Give a man a fish and you feed him for a day; teach a man to fish and you feed him for a lifetime" – Florian F. Dec 08 '14 at 21:29
  • More about delegate: http://www.sitepoint.com/event-delegation-with-jquery/ – MH2K9 Dec 09 '14 at 03:27