jQuery autocomplete and handling the value / label issue
Asked Answered
A

2

6

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");
});
Appetizing answered 20/1, 2012 at 6:53 Comment(0)
D
17

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/

Divisive answered 20/1, 2012 at 15:18 Comment(0)
H
0

You mean that? Change "area:" to new one?

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


<script>
 $(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);
    // working like this?
    $('#area').text(ui.item.label);
    // $('#area').text('this is what I want');
    }
 });
   //alert("this loaded");
 });
 </script>
Hillis answered 20/1, 2012 at 6:57 Comment(2)
Sorry - not getting what you're saying. Right now, it's populating meta-area with the value variable and I'd like to have the label.Appetizing
It's possible to get label like this $('#meta-area').text(ui.item.label);. It works.Hillis

© 2022 - 2024 — McMap. All rights reserved.