Add setValue and getValue to JQueryUI Autocomplete widget

by Spencer Wasden

HTML

<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<div class="ui-widget">
    <label for="tags">Tags: </label>
    <input id="tags" /> <br/>
    <span id="dropdown_list"></span>
    
    <button class='setValueClick' value='2' ele='tags'>Set value to 2</button>
    <button class='getValueClick' ele='tags'>Get value</button>
</div>

JavaScript

$(document).on('click', 'button.setValueClick', function(){
    //obtain <input> element that should be changed
    var ele = $('#' + $(this).attr('ele'));
    //call setValue from the autocomplete widget,
    //passing the value from the button's value attribute
    ele.autocomplete('setValue', $(this).attr('value'));
});
$(document).on('click', 'button.getValueClick', function(){
    //obtain <input> element that should be changed
    var ele = $('#' + $(this).attr('ele'));
    //alert the returned value from the autocomplete getValue method
    //note that you could do anything with this, instead of just alert
    alert(ele.autocomplete('getValue'));
});

$(function() {
    var availableTags = [
        { id: 1, label: 'one' },
        { id: 2, label: 'two' },
        { id: 3, label: 'three' },
        { id: 23, label: 'two-thirds' }
    ];

    $.widget("ui.autocomplete", $.ui.autocomplete, {
        setValue: function(id) {
            //get the actual input field instead of the jQuery autocomplete object
            var input = $(this.element[0]);
            //loop through availableTags, 
            //v will be an object within the array
            
            var tags = $(this.element[0]).autocomplete( "option", "source" );
            
            $.each(tags, function(k, v){
                //if the id property of the object matches the id passed to setValue,
                //set the input's value to the label property of the object 
                if(v.id == id){
                    input.val(v.label);
                    //if found, break the loop to save precious resources
                    return false;
                }
            });
        },
        getValue: function(){
            //get the actual input field instead of the jQuery autocomplete object
            var val = $(this.element[0]).val();
            //this is what will be returned, 
            //if no corresponding availableTag object matches,
            //false will be...