views:

127

answers:

1

I want to filter the autocomplete results based on the selected option in a select input.

sample json data:

[{"ContactId":"8590051631","ContactType":Company,"Name":"Test },{""ContactId":"8590049225","ContactType":Person,"Name":"TestName}]

here's my markup

<div>

<select class="type">
<option>Person</option>
<option>Company</option>
</select>

<input type="text" class="name" />

</div>


 $('.name').autocomplete("http://services.mydomain.com/rest/ia/findcontact", {
            dataType: 'jsonp',
            extraParams: {
                limit: '',
                timestamp: '' }
            },
            parse: function(data) {
                var items = data;
                var parsed = [];
                if (items != null || items != undefined) {
                    for (var i = 0; i < items.length; i++)
                        parsed[i] = { data: [items[i]], value: items[i].ContactId, result: [items[i].Name] };
                }
                return parsed;
            },
            formatMatch: function(d,i,t) {
            alert($(this).parent().find(".type").val());
               // do some filtering here?
            }

        });    

It seems like I should use formatMatch option to filter the results but I can't get this to work. How do I filter the results based on the selected option value?

A: 

I am guessing in the parse function, you can obtain current selected type, and ignore the item if it's not the selected type?

parse: function(data) {
    var items = data;
    var parsed = [];
    if (items != null || items != undefined) {
        //get current type
        var selectedType = $(this).parent().find(".type").val();
        for (var i = 0; i < items.length; i++) {
            if (selectedType == items[i].ContactType){
                //just append to the array so you don't need to worry about missing indices.
                parsed.push({ data: [items[i]], value: items[i].ContactId, result: [items[i].Name] });
            }
        }
    }
    return parsed;
}
coolnalu
Thanks for the reply and suggestion. I was thinking of that too and tried but I get 'undefined' for var selectedType = $(this).parent().find(".type").val(); Looks like it can't find the select input. How do I find other inputs within the same div as the autocomplete input?
I am not 100% sure about what does $(this) point to in the parse function. Maybe try alert($(this)) to make sure it's pointing to the text box element? If that works then finding the select box is trivial. $(this).prevAll("select.type").val();
coolnalu
Looking in Firebug $(this) is the autocomplete plugin. I tried $(this).parent().find(".type").val(); and $(this).prevAll("select.type").val(); but neither work.
Found the solution in this post.http://stackoverflow.com/questions/2064651/how-do-i-get-the-id-of-the-control-calling-the-jquery-autocomplete-function