0

I have the following jQuery code:

$("#file-upload").change(function () {
    if (this.files && this.files[0]) {
        $('#cancel-image-upload').html('<button type="button" class="btn btn-warning" id="cancel-upload-button" style="margin-right:15px;">cancel</button>');
    }
    else
        $("#image-preview").attr("src", "http://placehold.it/200x150");
});


$('#cancel-upload-button').click(function () {
        $("#file-upload").replaceWith('<input type="file" id="file-upload" name="file" accept="image/*">');
    });

What this code does is to display cancel button after file has been chosen, and the button should be able to delete it when clicked. I tried the code above but it didn't work for some reason. Why and how can I fix it? thanks!

Pete
  • 57,112
  • 28
  • 117
  • 166
Nave Tseva
  • 868
  • 8
  • 24
  • 47

2 Answers2

2

Try

$(document.body).on('click', '#cancel-upload-button', function () {
    $("#file-upload").replaceWith('<input type="file" id="file-upload" name="file" accept="image/*">');
});

You need a live binding in order to keep the event on the cancel button, since you're removing it from the DOM in the #file-upload change() callback.

wiesion
  • 2,349
  • 12
  • 21
0

Add #cancel-upload-button's click handler just after adding the control ie inside the if loop.

Abe
  • 31
  • 4