WooCommerce Select2匹配美国/加拿大等,以字符串开头表示状态,而不仅仅是任何匹配项

时间:2019-06-07 22:24:36

标签: woocommerce jquery-select2 dropdown matcher

WooCommerce在州和国家/地区的送货和帐单地址字段中使用select2。我要这样做,以便当您搜索ka时,最高结果是Kansas而不是Alaska

我检查了select2的文档,发现了这一点:

https://select2.org/searching#customizing-how-results-are-matched

但是该解决方案适用于有孩子的情况。我不知道如何编辑记录的示例以使其与WooCommerce兼容。因此,另一篇文章建议这样做:

function matchCustom(term, text) {
  console.log('matcher is running');
  if (text.toUpperCase().indexOf(term.toUpperCase()) == 0) {
    return true;
  }
}
jQuery( document ).ready(function() {

  $(".state_select").select2({
    matcher: matchCustom
  });
});

使用上面的代码,当我搜索ka时,最高结果是Alaska而不是Kansas

我看了以下SO问题:

jquery select2 plugin how to match only beginning of word

jquery select2 plugin how to get only the result 'myString%'

select2 search - match only words that start with search term

1 个答案:

答案 0 :(得分:2)

您可以这样做:

  1. 脚本文件(我将其命名为PIPENV_VENV_IN_PROJECT=1 pipenv sync -d ):

    my-wc-country-select.js

    Reference

  2. 在前端加载文件:(此代码将在主题功能文件中显示)

    jQuery( function( $ ){
        if ( ! $().selectWoo ) {
            return;
        }
    
        // Based on <https://select2.org/searching#customizing-how-results-are-matched>
        function matchCustom(params, data) {
            // If there are no search terms, return all of the data
            if ($.trim(params.term) === '') {
                return data;
            }
    
            // Do not display the item if there is no 'text' property
            if (typeof data.text === 'undefined') {
                return null;
            }
    
            // `params.term` should be the term that is used for searching
            // `data.text` is the text that is displayed for the data object
            var s = $.trim( params.term ).toLowerCase();
            var s2 = $.trim( data.text ).toLowerCase();
            if ( s === s2.substr( 0, s.length ) ) {
                return data;
            }
    
            // Return `null` if the term should not be displayed
            return null;
        }
    
        function country_select_select2() {
            // Apply the custom "matcher" to the country and state drop-downs.
            $( 'select.country_select:visible, select.state_select:visible' ).selectWoo( {
                // We're just changing this option.
                matcher: matchCustom
            } );
        }
    
        country_select_select2();
    
        $( document.body ).bind( 'country_to_state_changed', function() {
            country_select_select2();
        });
    } );
    

    确保将wp_enqueue_script( 'my-wc-country-select', 'path/to/my-wc-country-select.js', [ 'wc-country-select' ] ); 添加为依赖项。