-->

AutoComplete-devbridge: update params on change fr

2019-07-21 21:20发布

问题:

I'm currently using this plugin:

https://github.com/devbridge/jQuery-Autocomplete

What I want is that when I selected an option from the name text field I can get that value and put it as a parameter on the address text field where the options in the address field is limited only where name exist in that address.

And same goes when I selected an option from the address field the options in the name field is limited only to names of persons who lives on that address.

Here's my code:

$(document).ready(function(){
    var name = '';
    var add = '';

    $('#name').change(function() {
        name = $('#name').val();
    });

    $('#add').change(function() {
        add = $('#add').val();
    });

    $('#name').devbridgeAutocomplete({
        serviceUrl: 'search/name',
        minChar: 2,
        params: {add: add},
        onSelect : function(suggestion) {
            $('#name').val(suggestion.value);
        }
    });

    $('#name').devbridgeAutocomplete({
        serviceUrl: 'search/address',
        minChar: 2,
        params: {name: name},
        onSelect : function(suggestion) {
            $('#name').val(suggestion.value);
        }
    });
});

I don't know why it's not working, did I do it right or am I doing it all wrong? Please help!

Has anyone else had this problem or know of a solution?

回答1:

Because your variables are strings, they are passed as values and not a reference. When data in the "#add" changes you need to update parameters on "#name" input autocomplete instance:

$('#add').change(function() {
    var add = $('#add').val();
    $('#name').devbridgeAutocomplete().setOptions({
        params: { add: add }
    });
});


回答2:

although this is few year back question, I came across this issue so I post my solution here to help out anyone that might need this for Devbridge additional params

$('#search').autocomplete({
    serviceUrl: "search/name",
    type: "POST",
    dataType: "json",
    paramName: "name",
    params: {
        middle: function(){
            return $("#middle").val();
        },
        last: function(){
            return $("#last").val();
        },
        //no value return for using last:$("#last").val()
    },
    minChars: 3,
    showNoSuggestionNotice: true,
    noSuggestionNotice: "No results found",
    transformResult: function(response) {
        if (response){
            return {
                suggestions: $.map(response.results, function(dataItem) {
                    return { value: dataItem.name.trim(), data: dataItem.id, object: dataItem };
                })
            };
        }
        else{
            return {
                suggestions: []
            };
        }
    },
    onSelect: function(suggestion){
        //suggestion.object contain all values pass thru, no need to call again
    },
});