Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery autocomplete and handling the value / label issue

I'm trying to have a jQuery autocomplete. I have specified some data but when I select an item on the drop down, it always pushes the value into the meta-area elements. I want the label. How to do this? Trying to get it to show the label in #meta-area rather than the value.

HTML:

 ...
 area:<input type='text' size='20' id='meta-area' />
   <input type='hidden' id='meta_search_ids' value='' />
 ...

JavaScript:

$(document).ready(function(){
    var data =[
        {'label':'Core','value':1},
        {'label':' Selectors','value':2},
        {'label':'Events' ,'value':3}]; 

        $("#meta-area").autocomplete({source:data,
            select: function(e, ui) {
                $("#meta_search_ids").val(ui.item.value);
                // this part is not working
                //$(this).val(ui.item.label);
                $('#meta-area').text('this is what I want');
            }
        });
    //alert("this loaded");
});
like image 623
timpone Avatar asked Jan 20 '12 06:01

timpone


1 Answers

The default action of a select event places ui.item.value inside the input. You need to use preventDefault with your event handler:

$(document).ready(function(){
    var data =[
        {'label':'Core','value':1},
        {'label':' Selectors','value':2},
        {'label':'Events' ,'value':3}]; 

    $("#meta-area").autocomplete({
        source:data,
        select: function(e, ui) {
            e.preventDefault() // <--- Prevent the value from being inserted.
            $("#meta_search_ids").val(ui.item.value);

            $(this).val(ui.item.label);
        }
    });
    //alert("this loaded");
});

Example: http://jsfiddle.net/UGYzW/6/

like image 91
Andrew Whitaker Avatar answered Nov 06 '22 16:11

Andrew Whitaker