Tuesday 28 March 2023

Select2 not populating hidden field with values

I have select2 working in my WordPress plugin, and I am able to search for pages when I type into a field and click on them. You know how that works.

The problem is that the ids of the pages I select are not being added into the "exclusion_ids" hidden field. Here's my code:

<input name="exclusions" type="text" class="select2" />
<input name="exclusion_ids" type="hidden" />

<script>
    jQuery(document).ready(function($) {
        $('.select2').select2({
            ajax: {
                url: ajaxurl,
                dataType: 'json',
                delay: 250,
                data: function (params) {
                    return {
                        q: params.term,
                        action: 'search_posts',
                        nonce: '<?php echo wp_create_nonce( "search_posts_nonce" ); ?>'
                    };
                },
                results: function (data) {
                    var results = [];
                    $.each(data, function(index, post) {
                        results.push({
                            id: post.id,
                            text: post.title
                        });
                    });
                    return {
                        results: results
                    };
                },
                cache: true
            },
            minimumInputLength: 3,
            placeholder: 'Type to search for posts',
            tags: true,
            tokenSeparators: [',']
        });

        jQuery(document).on('change', '.select2', function() {
            var ids = [];
            $('.select2').find(':selected').each(function() {
                ids.push($(this).val());
            });
            $('input[name="exclusion_ids"]').val(ids.join(','));
        });
    });

    // Debugging
    jQuery(document).on('change', '.select2', function() {
        console.log('Change event fired!');
        var ids = [];
        jQuery('.select2').find(':selected').each(function() {
            ids.push(jQuery(this).val());
        });
        console.log('The ids :', ids);
        console.log('Hidden field value: ', jQuery('input[name="exclusion_ids"]').val());
    });
</script>

There are no errors in the console.

My debugging returns this:

Change event fired!

The ids : []
    length: 0
    [[Prototype]]: Array(0)

Hidden field value: 

When I inspect the hidden field while selecting a page from the field, I can see it suddenly change from this...

<input name="exclusion_ids" type="hidden">

...to this...

<input name="exclusion_ids" type="hidden" value="">

...so I do know the change event is firing and targeting the correct hidden field. So the problem looks like it's not getting the IDs.

Any ideas on how to fix this?



from Select2 not populating hidden field with values

No comments:

Post a Comment