Fullstack web developer, creative thinker, businessman and entrepeneur who helps his customers achieve online success

A tiny lightweight custom select input for jQuery

I needed to programmatically open and close a select input, so I built my jQuery plugin to handle it

Kevin From

The problem

Recently at a workshop with a customer of mine, we brainstormed on their checkout flow and realised that you could actually press the "Checkout" button, before all required data was given, including product variants. The product being a t-shirt had variants such as color and size. The customer wanted to have the Checkout button disabled by default untill all required input fields were filled out, which meant I had to programmatically check whether or not a required field was filled out or not and then open the select if it had not been filled out yet.

In modern browsers such as Google Chrome, you simply open a select tag in JavaScript. First of all it has no function to do this directly. Second of all, if you were to programatically trigger a click on the select, the custom event you are triggering would not be considered safe by Google Chrome, and would therefore not open the select. This ultimately meant, that I had to use a custom select - rendering a custom element, which updates a hidden input field of the select. I started looking for existing libraries such as selectize.js, but found that it increased my bundle size quite a lot, which I was not satisfied with and knew the customer wouldn't be aswell.

The solution

This site is already using jQuery, so I figured, I'd just write my own jQuery plugin, which takes a select input, changes it to a hidden input field and then renders a div in the place of the original select tag. It then adds event listeners to trigger clicks on the dropdown and items inside it, so the hidden input field gets updated with the correct value.

Check out the source code here and the demo here!