Select2 不使用值填充隐藏字段

问题描述 投票:0回答:0

我的 WordPress 插件中有 select2,当我在字段中输入并单击它们时,我能够搜索页面。你知道它是如何工作的。

问题是我选择的页面的 ID 没有被添加到“exclusion_ids”隐藏字段中。这是我的代码:

<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>

控制台没有报错

我的调试返回这个:

Change event fired!

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

Hidden field value: 

当我从字段中选择一个页面时检查隐藏字段时,我可以看到它突然从这个改变...

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

...到这个...

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

...所以我知道更改事件正在触发并针对正确的隐藏字段。所以问题看起来不是获取 ID。

关于如何解决这个问题的任何想法?

javascript wordpress jquery-select2
© www.soinside.com 2019 - 2024. All rights reserved.