Blog

Chosen Select Create New Value

Jun 18 2016

jQuery jQuery Plugin Frontend

Once in a while I use a great jQuery plugin from Harvest called Chosen. It is design to make selects and multi selects a lot more user friendly.

Out of the box it will convert a standard select into a searchable list allowing the user to type their desired option into an input box.

If the desired option isn't available the user is given an error message. In most instances this is probably fine but there have been a number of times where I would rather create a new option based on the new user input.

A few folks have forked the official git repo and while they work they also need to be maintained.

I have a more simple solution that doesn't hack the core and is quite simple.

The HTML

This is a basic select element with the class chosen that starts the plugin. We are going to append our new user created elements to the end of this and select them for our user.

<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

First let's Start Chosen

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

Any Time the text input in the Chosen select changes we need to run some code. We are going to watch the chosen-search input selector for changes, this will trigger onBlur.

$(".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');
});



Menu

Contact Us

Contact form submitted!
We will be in touch soon.