user866933 user866933 - 4 months ago 21
Javascript Question

jquery autocomplete How to set label and how to get value?

I have a dynamic input field created with class name as sub-category.
On key press autocomplete is working fine, from which i can select one.

Working code for that is below

$("body").on('keypress', 'input.sub-category', function () {
var availableTags = [
{label:"ActionScript", value:"1"},
{label:"ActionScript1", value:"11"},
{label:"ActionScript2", value:"12"},
{label:"ActionScript3", value:"13"},
{label:"ActionScript4", value:"14"},
];
$(this).autocomplete({
source: availableTags,
});
});


When i select one of the autosuggested text say 'ActionScript', it's value (1) should be available in the below code, how i can access it? On select alert function is working fine, so just need to know how to access value of the selected label.

$("body").on('autocompleteselect', 'input.sub-category', function () {
alert('here');
});


In addition to that i would like to know how to set the selected text in the input box rather than it's value.

Answer

you need to include jquery-ui file "https://code.jquery.com/ui/1.12.0/jquery-ui.js" in your file and just replace

 $("body").on('autocompleteselect', 'input.sub-category', function () {
        alert('here');
});

with the following lines.

$("body").on('autocompleteselect', 'input.sub-category', function (event,ui)     {
    alert(ui.item.label);
    alert(ui.item.value);

});

and

$(this).autocomplete({
        source: availableTags,
    });

with

$(this).autocomplete({
        source: availableTags,
        select:function(event,ui){
           $(".sub-category").val(ui.item.label);return false;
        }
    });

and this will work fine for more info please go on following link

http://api.jqueryui.com/autocomplete/