Arihant
Arihant

Reputation: 4047

jQuery UI autocomplete text with attribute

I am using the jQueryUI autocomplete for a textbox. I want the textbox to be filled in a way that as soon as the textbox is autocompleted, a variable should be set to a particular value associated with that particular autocomplete option.

Source for autocomplete:

var availableTags = ["Air University","Alabama A&M University",
"Alabama State University","Athens State University",...];
//list very long, 2000+

I think the source should be converted as a JSON object such as

[{ "id":"1", "name":"Air university";}....];

And then when Air university is selected, a variable should be set to the value in 'id'.

Code:

 $( "#tags" ).autocomplete({
  source: function(request, response) {
    var results = $.ui.autocomplete.filter(availableTags, request.term);

    response(results.slice(0, 10));
},
  minLength:5
});

How can this be done?

Upvotes: 0

Views: 802

Answers (1)

Ranjana
Ranjana

Reputation: 815

Created jsfiddle to show how we can get the id of selected option. https://jsfiddle.net/aqbjb5k9/ Hope this helps.

$( function() {
var availableTags = [
  {
    value: "Air University",
    id: "1"
  },
  {
    value: "Alabama A&M University",
    id: "2"
  },
  {
    value: "Alabama State University",
    id: "3"
  }
];
$( "#tags" ).autocomplete({
  source: availableTags,
  select: function( event, ui ) {
    var result_selected = ui.item.id;
    alert(result_selected );     
    return false;
  }
});
});

Upvotes: 1

Related Questions