Selectize.js is a javascript library that allows you to offer more complex HTML select boxes, such as combining a select and an input box, commonly known as an autocomplete combobox. Most importantly, they have a built-in stylesheet for Bootstrap 3. However, I discovered a problem when you are trying to add another form field dynamically, specifically using jQuery’s .clone() function.
However, selectize() does not clone well… it breaks horribly. The key you must .destroy() the selectize() prior to cloning. Of course, another problem occurs then: The select element, upon selectize.destroy(), will reset the value to the last option. Solution? Store the value, destroy(), then set the value.
// When add button is clicked $('#add').on('click',function(){ $('.combobox').each(function(){ // do this for every select with the 'combobox' class if ($(this)[0].selectize) { // requires [0] to select the proper object var value = $(this).val(); // store the current value of the select/input $(this)[0].selectize.destroy(); // destroys selectize() $(this).val(value); // set back the value of the select/input } }); $('#monsters .form-group:first') .clone() // copy .insertAfter('#monsters .form-group:last'); // where selectizeme(); // reinitialize selectize on all .combobox }); |