Chosen Select Create New Value

jquery jquery-plugin frontend chosen select javascript ui

Extending the Chosen jQuery plugin to allow users to create new select options dynamically

Chosen Select with Dynamic Option Creation

I frequently use Chosen, an excellent jQuery plugin from Harvest that makes select and multi-select elements much more user-friendly. Out of the box, it converts standard selects into searchable lists where users can type to find options.

By default, if a desired option isn’t available, users get an error message. However, there are times when I’d prefer to allow users to create new options based on their input.

While some have forked the official repository to add this functionality, those forks require maintenance. I have a simpler solution that doesn’t modify the core plugin.

The HTML

Start with a basic select element using the chosen class to initialize the plugin. We’ll append new user-created options to this select.

<select name="demo" class="chosen">
  <option value="1">Option 1</option>
  <option value="2">Option 2</option>
  <option value="3">Option 3</option>
  <option value="4">Option 4</option>
</select>

The jQuery Implementation

Initialize Chosen

$(".chosen").chosen();

Add Dynamic Option Creation

Watch for changes in the Chosen search input. This triggers when the user finishes typing (onBlur event).

$(".chosen-search input").change(function() {
  // Capture the new user created value
  var newOption = $(".chosen-search input").val();

  // Format and append the new option
  $(".chosen").append('<option value="'+newOption+'">'+newOption+'</option>');

  // Select the New option for the user
  $(".chosen option:last-child").attr('selected', 'selected');

  // Reload Chosen to display the new option
  $(".chosen").trigger('chosen:updated');
});

How It Works

  1. User types in the Chosen search input
  2. onBlur event triggers when they finish typing
  3. New option created and appended to the select element
  4. Option automatically selected for the user
  5. Chosen refreshed to display the new option in the interface

Benefits

  • No core modifications - Plugin remains untouched
  • Simple implementation - Minimal code required
  • Automatic selection - New options are immediately chosen
  • Maintains compatibility - Works with existing Chosen features
  • Easy to customize - Can be extended for validation, formatting, etc.

Considerations

  • Data persistence: Remember to handle saving new options to your backend
  • Validation: Consider adding checks for duplicate or invalid values
  • User feedback: You might want to add visual confirmation when new options are created
  • Accessibility: Ensure screen readers announce the new options properly

This approach provides a clean, maintainable way to extend Chosen’s functionality without forking the plugin or dealing with upstream changes.