jQuery hidden input value on change doesn't trigger

225 views Asked by At

Concrete5 has an image picker which updates a hidden input value with a picture ID after the picture is selected, e.g.:

<input name="pictureID" value="22" type="hidden">

I need to load the selected image on an Add Block form after selecting the image. That is, to load the image (I can get the image URL by the ID) after the hidden input gets updated with the ID.

This only works if the image has been selected and saved before:

$('input[name=pictureID]').on('change', function() {
...
}).trigger('change');

But if the image picker is cleared and a new image is selected, the above doesn't work as the hidden input is dynamically added after selecting the image. Well, fine, I tried this instead:

$(document).on('change', 'input[name=pictureID]', function() {
...
}).trigger('change');

But that doesn't work either. Probably because the change in on a hidden element which has to be triggered to get the new value. If I was changing the value myself, I would have triggered it. But how do I trigger the hidden input value change if I need to know when it's changed by the system in the first place?

How can I load an image on updating a hidden input value?

1

There are 1 answers

0
Jozzeh On

Here's javascript code that triggers when a file is selected
+
I've added a function (handleCustomImageChoice) which receives all the data of the selected file.

$(document).ready(function(){
    function handleCustomImageChoice(result){
        console.log(result);

        //check the result object to get the url of the file
        //EXAMPLES :
        //get thumbnail url =
        console.log(result.files[0].resultsThumbnailImg);

        //get full size url =
        console.log(result.files[0].url);
    }

    $(document).on('change', 'form', function(){
        //when a file is selected in the file manager, then the nearest form is triggered to 'change'...
        //first check if the form that is triggered has the required input
        let closestForm = $('input[name=pictureID]').closest('form').attr('action');
        let currentForm = $(this).attr('action');

        if(closestForm == currentForm){
            //here your action when the hidden input value is changed
            console.log($('input[name=pictureID]').val());
            let fileID = $('input[name=pictureID]').val();
            if(fileID != 0){
                // ConcreteFileManager.getFileDetails(fileID , callback);
                ConcreteFileManager.getFileDetails(fileID, handleCustomImageChoice);
            }
        }
    });
});

During my research to solve this issue, I've also encountered a javascript object called 'ConcreteEvent'... That object handles JS events from the core ... However I could not subscribe to the 'FileManagerSelectFile' event. So I can't give you that code... but the code above should give you what you need.