jQuery toggleClass example
Toggle class name on click in jQuery
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<div class="ui-widget">
<label for=“tags”>Input1: </label>
<input id="dynamic">
</div>
<div class="ui-widget">
<label for="tags">Input2: </label>
<input id="static">
</div>
<div class="ui-widget">
<label for="input3">Input3: </label>
<input id="both">
</div>
JavaScript
// This will be your data structure for the autocomplete
//
// The keys of this object are the input selectors,
// the values are the autocomplete values
//
// In your app you will probably be creating this object dynamically
// from some extrenal data
const dataBySelector = {
'#dynamic': ["JavaScript", "Python", "Ruby"],
'#static': ["C", "C++", "Java"],
'#both': ["JavaScript", "Python", "Ruby", "C", "C++", "Java"],
// Now you can also do some silly stuff like this :)
'input:not(:disabled):visible': ["JavaScript", "Python", "Ruby"]
};
// Your function will accept the data object from above and initialize the autocompletes
function show_options(data) {
Object.keys(data).forEach(function(selector) {
// First we grab the data for this selector
const dataForAutocomplete = data[selector];
// Then we initialize the autocomplete and store the jQuery object
// so that you don't need to call $(this) all the time (a little performance optimization)
const $autocomplete = $(selector).autocomplete({
source: dataForAutocomplete,
minLength: 0
})
.focus(function() {
$autocomplete.autocomplete("search", $autocomplete.val())
});
})
}
// Then you call the function when necessary
show_options(dataBySelector);