ArticleZip > Twitter Bootstrap Typeahead Id Label

Twitter Bootstrap Typeahead Id Label

Twitter Bootstrap's Typeahead feature is a powerful tool that allows users to search and select items from a pre-populated list as they type. One essential aspect of working with Typeahead is understanding how the "id" and "label" attributes function.

In the context of Twitter Bootstrap Typeahead, the "id" refers to the unique identifier associated with each item in the dataset. This identifier helps differentiate between different items when they are selected or manipulated. On the other hand, the "label" is the human-readable information that is displayed to the user in the dropdown list. It serves as the visual representation of the item being selected.

When integrating Typeahead into your web application, you will often work with a dataset that contains objects with both "id" and "label" properties. These objects can be structured in various ways but typically follow a key-value pair format.

For example, you might have an array of objects with the following structure:

Javascript

var data = [
    { id: 1, label: 'Apple' },
    { id: 2, label: 'Banana' },
    { id: 3, label: 'Orange' }
];

In this scenario, each object in the dataset contains an "id" and a "label" property. When a user selects an item from the Typeahead dropdown list, the corresponding "id" value is often stored in a hidden input field, allowing you to capture the unique identifier associated with the selected item.

To implement this functionality, you can leverage the events provided by Typeahead, such as the "select" event. When an item is selected, you can access both the "id" and "label" properties of the selected object and handle them accordingly.

Here's a simple example of how you can capture the "id" and "label" of the selected item using jQuery and Typeahead:

Javascript

$('#typeahead-input').typeahead({
    source: data,
    onSelect: function(item) {
        var selectedId = item.id;
        var selectedLabel = item.label;
        // Handle the selected id and label as needed
    }
});

By understanding the distinction between the "id" and "label" attributes in Twitter Bootstrap Typeahead, you can enhance the user experience of your application by providing clear and structured data interactions. This knowledge empowers you to create dynamic and interactive search functionalities that elevate the usability of your web projects.

×