user123456789 user123456789 - 3 years ago 55
jQuery Question

how can i get selected value in jquery auto suggest plugin

Here i'm using a auto-suggest plugin,

i'm facing a problem with getting the selected value.

var data = {items: [
{value: "21", name: "Mick Jagger"},
{value: "43", name: "Johnny Storm"},
{value: "46", name: "Richard Hatch"},
{value: "54", name: "Kelly Slater"},
{value: "55", name: "Rudy Hamilton"},
{value: "79", name: "Michael Jordan"}
]};

$("#search_query_top").autoSuggest(data.items, {
selectedItemProp: "name",
selectionLimit: 1,
searchObjProps: "name",
startText: "Search by name,",
resultClick: function(items){ console.log(items);}
});


Please, Can any one help me regarding this,

Here is the documentation for plugin

Similar Question from stack overflow

Thanks

Answer Source

Here is my solution for you :

//this will store all the results.
var mySearchResult = {};
$("#search_query_top").autoSuggest(data.items, {
    selectedItemProp: "name",
    selectionLimit: 3, 
    searchObjProps: "name",
    startText: "Search by name,",
    //each time i add a new item, i store it in the mySearchResult object
    selectionAdded: function(item){mySearchResult[(item.clone().find("a").remove().end().text())] = true},
    //each time i remove an item, i delete if from mySearchResult and i remove the item from the visual.
    selectionRemoved: function(item){delete mySearchResult[(item.clone().find("a").remove().end().text())]; item.remove();}
});

$('#sbmButton').click(function(e){

    var tab = [];
    for(var k in mySearchResult){
        tab.push(k); 
    }

    alert(tab.join("\n"));

});

A last bug still appear, the very first item you add is not removed from the display list items.

You can check this on this WORKING DEMO. I'll try to see what's going on about the little bug.

Hope it helped you.

EDIT : Check out the other answer that find a more "friendly" way to do the same things. You'll have to do some changes, but i think this is the best way. I really find this plug-in a bit tricky for finding this values. Finally i don't recommend this one.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download