[Almost Resolved] How to use jquery country selector in wordpress

I found a jquery country selector that i like alot. However, getting it working with wordpress is proving difficult. I have looked at many tutorials on getting jquery working with wordpress and it sort of helped. The selector I am talking about is found here COUNTRY SELECTOR
The files included are:

  • jquery.select-to-autocomplete.js
(function($){
  var settings = {
    'sort': false,
    'sort-attr': 'data-priority',
    'sort-desc': false,
    'autoselect': true,
    'alternative-spellings': true,
    'alternative-spellings-attr': 'data-alternative-spellings',
    'remove-valueless-options': true,
    'copy-attributes-to-text-field': true,
    'autocomplete-plugin': 'jquery_ui',
    'relevancy-sorting': true,
    'relevancy-sorting-partial-match-value': 1,
    'relevancy-sorting-strict-match-value': 5,
    'relevancy-sorting-booster-attr': 'data-relevancy-booster',
    'minLength': 0,
	  'delay': 0,
    'autoFocus': true,
    handle_invalid_input: function( context ) {
      var selected_finder = 'option:selected:first';
      if ( context.settings['remove-valueless-options'] ) {
        selected_finder = 'option:selected[value!=""]:first';
      }
      context.$text_field.val( context.$select_field.find( selected_finder ).text() );
    },
    handle_select_field: function( $select_field ) {
      return $select_field.hide();
    },
    insert_text_field: function( context ) {
      var $text_field = $( '<input type="text"></input>' );
      if ( settings['copy-attributes-to-text-field'] ) {
        var attrs = {};
        var raw_attrs = context.$select_field[0].attributes;
        for (var i=0; i < raw_attrs.length; i++) {
          var key = raw_attrs[i].nodeName;
          var value = raw_attrs[i].nodeValue;
          if ( key !== 'name' && key !== 'id' && typeof context.$select_field.attr(key) !== 'undefined' ) {
            attrs[key] = value;
          }
        };
        $text_field.attr( attrs );
      }
      $text_field.blur(function() {
        var valid_values = context.$select_field.find('option').map(function(i, option) { return $(option).text(); });
        if ( ($.inArray($text_field.val(), valid_values) < 0) && typeof settings['handle_invalid_input'] === 'function' ) {
          settings['handle_invalid_input'](context);
        }
      });
      // give the input box the ability to select all text on mouse click
      if ( context.settings['autoselect'] ) {
         $text_field.click( function() {
             this.select();
            });
      }
      var selected_finder = 'option:selected:first';
      if ( context.settings['remove-valueless-options'] ) {
        selected_finder = 'option:selected[value!=""]:first';
      }
      return $text_field.val( context.$select_field.find( selected_finder ).text() )
        .insertAfter( context.$select_field );
    },
    extract_options: function( $select_field ) {
      var options = [];
      var $options = $select_field.find('option');
      var number_of_options = $options.length;
      
      // go over each option in the select tag
      $options.each(function(){
        var $option = $(this);
        var option = {
          'real-value': $option.attr('value'),
          'label': $option.text()
        }
        if ( settings['remove-valueless-options'] && option['real-value'] === '') {
          // skip options without a value
        } else {
          // prepare the 'matches' string which must be filtered on later
          option['matches'] = option['label'];
          var alternative_spellings = $option.attr( settings['alternative-spellings-attr'] );
          if ( alternative_spellings ) {
            option['matches'] += ' ' + alternative_spellings;
          }
          // give each option a weight paramter for sorting
          if ( settings['sort'] ) {
            var weight = parseInt( $option.attr( settings['sort-attr'] ), 10 );
            if ( weight ) {
              option['weight'] = weight;
            } else {
              option['weight'] = number_of_options;
            }
          }
          // add relevancy score
          if ( settings['relevancy-sorting'] ) {
            option['relevancy-score'] = 0;
            option['relevancy-score-booster'] = 1;
            var boost_by = parseFloat( $option.attr( settings['relevancy-sorting-booster-attr'] ) );
            if ( boost_by ) {
              option['relevancy-score-booster'] = boost_by;
            }
          }
          // add option to combined array
          options.push( option );
        }
      });
      // sort the options based on weight
      if ( settings['sort'] ) {
        if ( settings['sort-desc'] ) {
          options.sort( function( a, b ) { return b['weight'] - a['weight']; } );
        } else {
          options.sort( function( a, b ) { return a['weight'] - b['weight']; } );
        }
      }
      
      // return the set of options, each with the following attributes: real-value, label, matches, weight (optional)
      return options;
    }
  };
  
  var public_methods = {
    init: function( customizations ) {
      
      if ( /msie/.test(navigator.userAgent.toLowerCase()) && parseInt(navigator.appVersion,10) <= 6) {
        
        return this;
        
      } else {
        
        settings = $.extend( settings, customizations );

        return this.each(function(){
          var $select_field = $(this);
          
          var context = {
            '$select_field': $select_field,
            'options': settings['extract_options']( $select_field ),
            'settings': settings
          };

          context['$text_field'] = settings['insert_text_field']( context );
          
          settings['handle_select_field']( $select_field );
          
          if ( typeof settings['autocomplete-plugin'] === 'string' ) {
            adapters[settings['autocomplete-plugin']]( context );
          } else {
            settings['autocomplete-plugin']( context );
          }
        });
        
      }
      
    }
  };
  
  var adapters = {
    jquery_ui: function( context ) {
      // loose matching of search terms
      var filter_options = function( term ) {
        var split_term = term.split(' ');
        var matchers = [];
        for (var i=0; i < split_term.length; i++) {
          if ( split_term[i].length > 0 ) {
            var matcher = {};
            matcher['partial'] = new RegExp( $.ui.autocomplete.escapeRegex( split_term[i] ), "i" );
            if ( context.settings['relevancy-sorting'] ) {
              matcher['strict'] = new RegExp( "^" + $.ui.autocomplete.escapeRegex( split_term[i] ), "i" );
            }
            matchers.push( matcher );
          }
        };
        
        return $.grep( context.options, function( option ) {
          var partial_matches = 0;
          if ( context.settings['relevancy-sorting'] ) {
            var strict_match = false;
            var split_option_matches = option.matches.split(' ');
          }
          for ( var i=0; i < matchers.length; i++ ) {
            if ( matchers[i]['partial'].test( option.matches ) ) {
              partial_matches++;
            }
            if ( context.settings['relevancy-sorting'] ) {
              for (var q=0; q < split_option_matches.length; q++) {
                if ( matchers[i]['strict'].test( split_option_matches[q] ) ) {
                  strict_match = true;
                  break;
                }
              };
            }
          };
          if ( context.settings['relevancy-sorting'] ) {
            var option_score = 0;
            option_score += partial_matches * context.settings['relevancy-sorting-partial-match-value'];
            if ( strict_match ) {
              option_score += context.settings['relevancy-sorting-strict-match-value'];
            }
            option_score = option_score * option['relevancy-score-booster'];
            option['relevancy-score'] = option_score;
          }
          return (!term || matchers.length === partial_matches );
        });
      }
      // update the select field value using either selected option or current input in the text field
      var update_select_value = function( option ) {
        if ( option ) {
          if ( context.$select_field.val() !== option['real-value'] ) {
            context.$select_field.val( option['real-value'] );
            context.$select_field.change();
          }
        } else {
          var option_name = context.$text_field.val().toLowerCase();
          var matching_option = { 'real-value': false };
          for (var i=0; i < context.options.length; i++) {
            if ( option_name === context.options[i]['label'].toLowerCase() ) {
              matching_option = context.options[i];
              break;
            }
          };
          if ( context.$select_field.val() !== matching_option['real-value'] ) {
            context.$select_field.val( matching_option['real-value'] || '' );
            context.$select_field.change();
          }
          if ( matching_option['real-value'] ) {
            context.$text_field.val( matching_option['label'] );
          }
          if ( typeof context.settings['handle_invalid_input'] === 'function' && context.$select_field.val() === '' ) {
            context.settings['handle_invalid_input']( context );
          }
        }
      }
      // jQuery UI autocomplete settings & behavior
      context.$text_field.autocomplete({
        'minLength': context.settings['minLength'],
        'delay': context.settings['delay'],
        'autoFocus': context.settings['autoFocus'],
        source: function( request, response ) {
          var filtered_options = filter_options( request.term );
          if ( context.settings['relevancy-sorting'] ) {
            filtered_options = filtered_options.sort( function( a, b ) { 
            	if (b['relevancy-score'] == a['relevancy-score']) {
            		return b['label'] < a['label'] ? 1 : -1;	
            	} else {
            		return b['relevancy-score'] - a['relevancy-score']; 
            	}
            } );
          }
          response( filtered_options );
        },
        select: function( event, ui ) {
          update_select_value( ui.item );
        },
        change: function( event, ui ) {
          update_select_value( ui.item );
        }
      });
      // force refresh value of select field when form is submitted
      context.$text_field.parents('form:first').submit(function(){
        update_select_value();
      });
      // select current value
      update_select_value();
    }
  };

  $.fn.selectToAutocomplete = function( method ) {
    if ( public_methods[method] ) {
      return public_methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
    } else if ( typeof method === 'object' || ! method ) {
      return public_methods.init.apply( this, arguments );
    } else {
      $.error( 'Method ' +  method + ' does not exist on jQuery.fn.selectToAutocomplete' );
    }    
  };
  
})(jQuery);

(function($){
	    $(function(){
	      $('select').selectToAutocomplete();
	      $('form').submit(function(){
	        alert( $(this).serialize() );
	        return false;
	      });
	    });
	  })(jQuery);

And these other files which I think wordpress already has jquery included. In fact I know it is… In the included folder!!! that was a joke… :frowning: sad face

  • jquery-1.11.1.min.js
  • jquery-ui.css
  • jquery-ui.min.js

This is the example page that was included

  • index.html
<!DOCTYPE html>
<html>
<head>
	<meta http-equiv="content-type" content="text/html; charset=utf-8" />
	<title>Select to Autocomplete</title>
	<script src="jquery-1.11.1.min.js"></script>
	<script src="jquery-ui.min.js"></script>
	<script src="jquery.select-to-autocomplete.js"></script>
	<script>
	  (function($){
	    $(function(){
	      $('select').selectToAutocomplete();
	      $('form').submit(function(){
	        alert( $(this).serialize() );
	        return false;
	      });
	    });
	  })(jQuery);
	</script>
	<link rel="stylesheet" href="jquery-ui.css">
	<style>
	  body {
	    font-family: Arial, Verdana, sans-serif;
	    font-size: 13px;
	  }
    .ui-autocomplete {
      padding: 0;
      list-style: none;
      background-color: #fff;
      width: 218px;
      border: 1px solid #B0BECA;
      max-height: 350px;
      overflow-x: hidden;
    }
    .ui-autocomplete .ui-menu-item {
      border-top: 1px solid #B0BECA;
      display: block;
      padding: 4px 6px;
      color: #353D44;
      cursor: pointer;
    }
    .ui-autocomplete .ui-menu-item:first-child {
      border-top: none;
    }
    .ui-autocomplete .ui-menu-item.ui-state-focus {
      background-color: #D5E5F4;
      color: #161A1C;
    }
	</style>
</head>
<body>
  <form>
    <select name="Country" id="country-selector" autofocus="autofocus" autocorrect="off" autocomplete="off">
      <option value="" selected="selected">Select Country</option>
      <option value="Afghanistan" data-alternative-spellings="AF افغانستان">Afghanistan</option>
      <option value="Åland Islands" data-alternative-spellings="AX Aaland Aland" data-relevancy-booster="0.5">Åland Islands</option>
      <!-- And so on... too long to post -->
    </select>
    
    <input type="submit" value="Submit">
  </form>
</body>
</html>

Anyway, I tried enqueueing the autocomplete js script and then a i wrote a small js script with the script that was shown in the head of the index.html file and enqueued that also. All I get is the select box turns into a text box. But no auto complete. I am sooooooo lost.

Ok here is what I have done so far and all i see is a regular select box still

add the 2 files

  • jquery.select-to-autocomplete.js
  • doitauto.js

to js directory in my child theme

doitauto.js is simply this

(function($){
	    $(function(){
	      $('select').selectToAutocomplete();
	      $('form').submit(function(){
	        alert( $(this).serialize() );
	        return false;
	      });
	    });
	  })(jQuery);

and i added this to my functions.php file in my child theme directory

add_action( 'wp_enqueue_scripts', 'ifautoselect' );
function ifautoselect() {
  wp_register_script( 'ifautocore', get_stylesheet_directory_uri() . '/js/jquery.select-to-autocomplete.js', array('jquery'), '5.5.0', false);
  wp_register_script( 'ifautodo', get_stylesheet_directory_uri() . '/js/doitauto.js', array('ifautocore'), '1.0.0', false);

  wp_enqueue_script( 'ifautocore' );
  wp_enqueue_script( 'ifautodo' );
}

any ideas? what am i doing wrong?

The first thing to check is whether there are any JavaScript errors in the console. Are you now loading two separate versions of jQuery?

I got it to work when I did this

add_action( 'wp_enqueue_scripts', 'ifautoselect' );

function ifautoselect() {
  wp_register_script( 'ifjq', get_stylesheet_directory_uri() . '/js/jquery-1.11.1.min.js');
  wp_register_script( 'ifjqmin', get_stylesheet_directory_uri() . '/js/jquery-ui.min.js');
  wp_register_script( 'ifautocore', get_stylesheet_directory_uri() . '/js/jquery.select-to-autocomplete.js', array('ifjqmin', 'ifjq'));
  wp_register_script( 'ifautodo', get_stylesheet_directory_uri() . '/js/doitauto.js', array('ifjqmin', 'ifjq', 'ifautocore'));

  wp_enqueue_script( 'ifjq' );
  wp_enqueue_script( 'ifjqmin' );
  wp_enqueue_script( 'ifautocore' );
  wp_enqueue_script( 'ifautodo' );
}

however other things quit working which also use jquery. So I believe there is a conflict somewhere.
I don’t know why it wont work otherwise. I’d like to just use the jquery that is included in wordpress so i dont have any conflicts.

OR is there a way to deregister those jquery files after they’ve been run to make the selector work.

my head hurts

Found a work around that works
It was messing up a plugin that i assume wasn’t loading jquery correctly into wp. I only use that plugin on one page and the country selector is used on a different page. So I did this and it works. Used an if statement to check if the page was the one i needed it on. if it is it loads it. if not it doesn’t problem solved. This is the best way i know to do it. If anyone knows of a better solution let me know.

add_action( 'wp_enqueue_scripts', 'ifautoselect' );

function ifautoselect() {
	if ( is_page('edit-details') ) {
		wp_register_script( 'ifjq', get_stylesheet_directory_uri() . '/js/jquery-1.11.1.min.js');
		wp_register_script( 'ifjqmin', get_stylesheet_directory_uri() . '/js/jquery-ui.min.js');
		wp_register_script( 'ifautocore', get_stylesheet_directory_uri() . '/js/jquery.select-to-autocomplete.js', array('ifjqmin', 'ifjq'));
		wp_register_script( 'ifautodo', get_stylesheet_directory_uri() . '/js/doitauto.js', array('ifjqmin', 'ifjq', 'ifautocore'));

		wp_enqueue_script( 'ifjq' );
		wp_enqueue_script( 'ifjqmin' );
		wp_enqueue_script( 'ifautocore' );
		wp_enqueue_script( 'ifautodo' );
	}
}

ugh… nevermind… didnt work. It messed up other plugins. It can’t be done easily obviously so screw it.

Still working on this. I really want it to work. Client wasn’t happy so i told him i would figure it out by tomorrow or his money back. If anyone wants to try and help me out, i would be very appreciative.

Here is the link to the jquery plugin im trying to get to work with the wordpress version of jquery.
JQuery country selector plugin - Main
Here is the “Instructions and FAQ” (didn’t help me much)
JQuery country selector plugin - Instructions & FAQ

Info needed is on these pages and/or posted above

Problem is (i think…). Using the jquery files included with this plugin is causing problems with jquery dependent plugins on wordpress.

So I take it there are no errors in the console. I would create a separate static HTML file and see if I could get it to work using the asset files included with wp core. Failing that I would analyze the sorce and customize it to work with those assets.

I haven’t run into this problem, so I don’t know, but I thought enqueue was supposed to deal with conflicts.

Maybe not,

Is jQuery in no-Conflict mode?

http://learn.jquery.com/using-jquery-core/avoid-conflicts-other-libraries/

http://api.jquery.com/jquery.noconflict/

So I tried to figure out the no conflict solution. I have narrowed the problem down to the jquery-ui.min.js
I have a plugins on wordpress
contact form DB
and
Aconix shortcodes

both of which stop working correctly when jquery-ui.min.js is enqueued

I don’t know how to put it into no conflict mode
If I can do that all would be perfect. Maybe

So i have learned that most jquery-ui files are custom additions to jquery. So something needs to be done to make this jquery-ui.min.js file to have no conflicts with other javascript files.

I have tried a lot of things (with very little knowledge) and have come up empty handed. It is probably something simple.

Do you know which file jquery-ui.min.js is having a conflict with? If not, then please put up a demo page that has the problem that you’re trying to fix, so that we can take a better look at what the problem may be and provide a workable solution for you.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.