Over the past year I've found myself moving from back-end development to something more akin to full-stack development. I've created the following jQuery plugin as a test of my hopefully-not-so-fledgling JavaScript/jQuery skills. The plugin is used to inject <option>
tags into the element(s) specified, and should follow the guidelines for creating basic plugins posted here.
(function($) {
$.fn.injectOptions = function(opts) {
opts = opts.map(function(opt) {
if (typeof opt === 'string')
return '<option>'+opt+'</option>';
return '<option value="'+opt.key+'">'+opt.val+'</option>';
});
var optHTML = opts.reduce(function(html, opt) { return html+opt; });
this.each(function() { $(this).html(optHTML); });
return this;
};
}(jQuery));
//example:
var fooArr = ["foo", "bar", "baz", "faz"];
var quxArr = [
{ key: 1, val: "qux"},
{ key: 2, val: "quux"},
{ key: 3, val: "quuux"},
];
$(".foo-options").injectOptions(fooArr);
$(".qux-options").injectOptions(quxArr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="foo-options">
</select>
<select class="qux-options">
</select>
<select class="qux-options">
</select>
Any/all suggestions are welcome!