Skip to content

Instantly share code, notes, and snippets.

@eddiemonge
Created February 17, 2012 01:16
Show Gist options
  • Save eddiemonge/1849494 to your computer and use it in GitHub Desktop.
Save eddiemonge/1849494 to your computer and use it in GitHub Desktop.
jQuery Simple Add Option ComboBox
(function($) {
$.fn.comboBox = function () {
var $this = $(this);
return $this.on("change", function(){
if ( $this.val() === 'add' ) {
$("<input type='text' />").blur(function(e) {
e.preventDefault();
var $i = $(this),
val = $i.val(),
selected = $this.find("option:contains('" + ucWord(val) + "')");
if (!selected.length) {
$("<option>", {
value: val,
text: val
}).insertBefore($this.find("option").last());
}
$this.val( selected.length ? selected.val() : val );
$i.empty().remove();
$this.show();
}).insertAfter( $this.hide() ).focus();
}
});
};
function ucWord( str ) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
})(jQuery);
// Usage: $('select').comboBox();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment