skip to Main Content

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?

3

Answers


  1. I copied your code on my localhost but filled the select with predefined data instead of AJAX request, and it works fine, so probably something is wrong with your request.

    Not sure what exactly you are requesting, but I guess it is WordPress posts, in WordPress id is uppercase, so it should be

    id: post.ID,
    

    not:

    id: post.id,
    

    I can be mistaken in that, because I do not 100% sure, what data is returned by your request. But for sure, issue is in the fetched data, not in the rest of the code.

    To confirm, you can try do use static data as a source:

    var data = [
        {
            id: 0,
            text: 'enhancement'
        },
        {
            id: 1,
            text: 'bug'
        },
        {
            id: 2,
            text: 'duplicate'
        },
        {
            id: 3,
            text: 'invalid'
        },
        {
            id: 4,
            text: 'wontfix'
        }
    ];
    
        $('.select2').select2({
            data: data,
            minimumInputLength: 1,
            placeholder: 'Type to search for posts',
            tags: true,
            tokenSeparators: [',']
        });
    

    Or log the $(this).val() to check what you are trying to push into array.

    Hope this will help.

    Login or Signup to reply.
  2. you have a bug in your code. you define var ids two times and so, you reset your values. this variable needs to be globally accessible. of course your array is empty in your "debugging" since you reset it (bc it doesn’t exist).

    and you may want to have a look at newer syntax let & const (basically, let is the new var and const is immutable (with exceptions though)), see var let and const – whats the difference

    let ids = []; // set it here!
    
    jQuery(document).ready(function($) {
        jQuery(document).on('change', '.select2', function() {
            var ids = []; // --> 1st time you set this variable
            // ...
        });
    });
    
    // Debugging
    jQuery(document).on('change', '.select2', function() {
        console.log('Change event fired!');
        var ids = []; // --> 2nd time you set this variable
        // ....
    });
    
    Login or Signup to reply.
  3. you can use it like this

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

    and

    
    jQuery(document).on('select2:select', '.select2', function(e) {
        var data = e.params.data;
        var ids = $('input[name="exclusion_ids"]').val();
        ids = ids ? ids.split(',') : [];
        ids.push(data.id);
        $('input[name="exclusion_ids"]').val(ids.join(','));
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search