Styling Default Select DropDown Fields

The default dropdown select field form element is difficult to style in CSS alone – it needs a bit of jQuery love, here is a guide to add some cleaner styling to change default dropdown sort select fields.

default-select-dropdown

Default Select Sort Field

 

Then one with some jQuery magic…

Sort select field looks a little better on this one

Using select2.js

So the above select field was transformed by using select2 which has a number of features manipulating the HTML select element.

Download the latest version from Github and unzip, you need to get 2 files to get up and running..

  • dist/css/select2.min.css
  • dist/js/select2.min.js

Using WordPress in this example add these to your WordPress child themes folder and also create a select2-init.js file in your js folder – so your structure will be…

  • yourtheme/css/select2.min.cs
  • yourtheme/js/select2.min.js
  • yourtheme/js/select2-init.js

Set Up Scripts in functions.php

<?php // <~ don't add me in
add_action('wp_enqueue_scripts', 'my_select_dropdown');
function my_select_dropdown() {
wp_enqueue_script( 'select2js', get_stylesheet_directory_uri() . '/js/select2.min.js', array( 'jquery' ), '4.0.6', true );
wp_enqueue_style( 'select2css', get_stylesheet_directory_uri() . '/css/select2.min.css' , array(), '4.0.6', 'all' );
wp_enqueue_script( 'selectinit', get_stylesheet_directory_uri() . '/js/select2-init.js', array( 'select2js' ), '1.0.0', true );
}
view raw functions.php hosted with ❤ by GitHub

 

Select the field to target

jQuery(document).ready(function($) {
$('.woocommerce-ordering select').select2(); // Add your target select field
});
view raw selectize-init.js hosted with ❤ by GitHub

In the select2-init.js file the ‘.woocommerce-ordering select’ field is targetted. Further jQuery parameters can be found on the select2.js page and Github.

 

default-select-dropdown-jquery-selectize

That’s it – you can target other select fields if required and also further style the select field by editing your CSS file.

Select2 shows a search box by default at the top of the dropdown, you can remove this by adding an option into the parameters.

$('.woocommerce-ordering select').select2({
	minimumResultsForSearch: Infinity
});

If you are actually wanting to do the WooCommerce dropdowns or have WooCommerce running you can use their fork of select2 called selectWoo to do the styling.

Leave a Comment