jQuery selector change not firing

I like to fire a change event when “#btnBrowse” click event fires. Here is a sample jQuery code;

$("#btnBrowse").click(function () {
   $("#btnReset").click();
   $("#xFileUpload").click();
});

$("#xFileUpload").change(function () {
   var filename = $('#xFileUpload')[0].files[0].name;
   filename = filename.replace(/\.[^/.]+$/, "");
   //alert(filename);
   $("#xFilename").val(filename);
   fileDoc.fileName = filename;
   fileDoc.fileContnet = $("#xFileUpload").get(0).files;
 });

It turns out that click event will be registered and fired on first click only. For subsequent clicks, I have to registered a change event and triggered it like this;

$("#btnBrowse").click(function () {
   $("#btnReset").click();
   $("#xFileUpload").click().trigger("change");
});

The cons of using this approach. It will work fine for the first click but all subsequent clicks will fire a change event on click event. The reason jQuery has registered two events for the element and execute them simultaneously.

The objective is to grab file from file system. The user should be able to use same file multiple time. The best alternative to achieve this objective is to clear the contents of HTML input type rather tweaking jQuery;

This is HTML file input;

<input type="file" id="xFileUpload" name="xFileUpload" class="form-control" style="display: none" />

This is jQuery code that will clear contents of this file;

$("#btnImportReset").click(function () {
   $('#xFileUpload').val('');
});

This is your final browse script section;

$("#btnBrowse").click(function () {
   $("#btnReset").click();
   $("#xFileUpload").click();
});

Since we are clearing out HTM contents and jQuery is smart enough to figure out change. The change event will be fired this time automatically with a change in HTML file input.

Resources

https://stackoverflow.com/questions/19194177/jquery-select-change-not-firing

https://stackoverflow.com/questions/4247264/how-to-trigger-jquery-change-event-in-code

FavoriteLoadingAdd to favorites
Spread the love

Author: Shahzad Khan

Software developer / Architect