Last active
December 23, 2015 15:45
-
-
Save wvengen/be89a2f8bfec7c038084 to your computer and use it in GitHub Desktop.
Form input to choose from existing values, while allowing to add new ones (based on select2).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// make sure you've loaded jquery & select2 - http://select2.github.io/select2/ | |
$(function() { | |
// choosing from a list of existing values in a textbox, with the option to add a new one | |
$('.select2-values:not(.no-select2)').each(function() { | |
var $this = $(this), | |
choices = $this.data('values'); | |
$this.select2({ | |
allowClear: true, | |
placeholder: ' ', // non-blank for allowClear to work | |
data: choices.map(function(c) { | |
return {id: c, text: c, new: false}; | |
}), | |
createSearchChoice: function(c) { | |
return {id: c, text: c+" (new value)", new: true}; | |
}, | |
createSearchChoicePosition: 'bottom', | |
formatResultCssClass: function(c) { | |
return c.new ? 'select2-result-freeform' : ''; | |
} | |
}); | |
}); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
<title>Select2 freeform example</title> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.js"></script> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.js"></script> | |
<script src="select2_freeform.js"></script> | |
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.css"> | |
<style type="text/css"> | |
body { min-height: 20ex; } | |
.select2-container { width: 100%; } | |
.select2-result-freeform { color: #666; font-style: italic; } | |
</style> | |
</head> | |
<body> | |
<h1>Select2 freeform example</h1> | |
<input class='select2-values' data-values='["Vegetables","Fruit","Nuts","Beverages"]' type='text' value='Vegetables' name='category'> | |
<p>This is a minimal example showing how a text-field can be used to show existing values first, while allow a new one.</p> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment