Handle selected event in autocomplete textbox using bootstrap Typeahead?
Asked Answered
A

9

27

I want to run JavaScript function just after user select a value using autocomplete textbox bootstrap Typeahead.

I'm searching for something like selected event.

Arbitration answered 3/3, 2012 at 16:35 Comment(2)
link to : https://mcmap.net/q/341927/-bootstrap-typeahead-js-add-a-listener-on-select-eventResign
True answer is not the one selected though...:(Epic
C
46
$('.typeahead').on('typeahead:selected', function(evt, item) {
    // do what you want with the item here
})
Cloris answered 28/3, 2013 at 4:55 Comment(2)
This approach works for twitter.github.io/typeahead.js not for the twitter bootstrap. (typeahead is now separated from twitter bootstrap)Drona
is there any way to get the key pressed for this handler? the evt var doesn't seem to have a 'which' properyWingover
H
19
$('.typeahead').typeahead({
    updater: function(item) {
        // do what you want with the item here
        return item;
    }
})
Halfbreed answered 25/12, 2012 at 0:14 Comment(0)
E
7

For an explanation of the way typeahead works for what you want to do here, taking the following code example:

HTML input field:

<input type="text" id="my-input-field" value="" />

JavaScript code block:

$('#my-input-field').typeahead({
    source: function (query, process) {
        return $.get('json-page.json', { query: query }, function (data) {
            return process(data.options);
        });
    },
    updater: function(item) {
        myOwnFunction(item);
        var $fld = $('#my-input-field');
        return item;
    }
})

Explanation:

  1. Your input field is set as a typeahead field with the first line: $('#my-input-field').typeahead(
  2. When text is entered, it fires the source: option to fetch the JSON list and display it to the user.
  3. If a user clicks an item (or selects it with the cursor keys and enter), it then runs the updater: option. Note that it hasn't yet updated the text field with the selected value.
  4. You can grab the selected item using the item variable and do what you want with it, e.g. myOwnFunction(item).
  5. I've included an example of creating a reference to the input field itself $fld, in case you want to do something with it. Note that you can't reference the field using $(this).
  6. You must then include the line return item; within the updater: option so the input field is actually updated with the item variable.
Each answered 30/5, 2013 at 10:49 Comment(0)
C
5

first time i've posted an answer on here (plenty of times I've found an answer here though), so here's my contribution, hope it helps. You should be able to detect a change - try this:

function bob(result) {
    alert('hi bob, you typed: '+ result);
}

$('#myTypeAhead').change(function(){
    var result = $(this).val()
    //call your function here
    bob(result);
});
Canebrake answered 21/3, 2012 at 22:17 Comment(1)
Have marked down because this is not the supported nor recommended way to handle selected elements on typeahead, see here: github.com/twitter/typeahead.js at: typahead:selectedEuphrates
P
4

According to their documentation, the proper way of handling selected event is by using this event handler:

$('#selector').on('typeahead:select', function(evt, item) {
    console.log(evt)
    console.log(item)
    // Your Code Here
})
Prosit answered 17/7, 2016 at 18:12 Comment(0)
B
3

What worked for me is below:

$('#someinput').typeahead({ 
    source: ['test1', 'test2'], 
    afterSelect: function (item) {
        // do what is needed with item
        //and then, for example ,focus on some other control
        $("#someelementID").focus();
    }
});
Belomancy answered 19/10, 2021 at 20:31 Comment(2)
The link no longer works.Cauca
No worries, the solution was already copied from there. I'm going to remove the link.Belomancy
S
1

I created an extension that includes that feature.

https://github.com/tcrosen/twitter-bootstrap-typeahead

Successor answered 4/4, 2012 at 0:23 Comment(2)
Link is broken right now. Is this the repository? github.com/tcrosen/twitter-bootstrap-typeaheadHaustellum
Sorry I updated the link a while ago, as of Apr 29th it works.Successor
W
0
source:  function (query, process) {
    return $.get(
        url, 
        { query: query }, 
        function (data) {
            limit: 10,
            data = $.parseJSON(data);
            return process(data);
        }
    );
},
afterSelect: function(item) {
    $("#divId").val(item.id);
    $("#divId").val(item.name);

}
Waterscape answered 14/9, 2017 at 20:45 Comment(0)
S
0

Fully working example with some tricks. Assuming you are searching for trademarks and you want to get the selected trademark Id.

In your view MVC,

@Html.TextBoxFor(model => model.TrademarkName, new { id = "txtTrademarkName", @class = "form-control",
   autocomplete = "off", dataprovide = "typeahead" })
@Html.HiddenFor(model => model.TrademarkId, new { id = "hdnTrademarkId" })

Html

<input type="text" id="txtTrademarkName" autocomplete="off" dataprovide="typeahead" class="form-control" value="" maxlength="100" />
<input type="hidden" id="hdnTrademarkId" />

In your JQuery,

$(document).ready(function () {
var trademarksHashMap = {};
var lastTrademarkNameChosen = "";

$("#txtTrademarkName").typeahead({
    source: function (queryValue, process) {
        // Although you receive queryValue, 
        // but the value is not accurate in case of cutting (Ctrl + X) the text from the text box.
        // So, get the value from the input itself.
        queryValue = $("#txtTrademarkName").val();
        queryValue = queryValue.trim();// Trim to ignore spaces.

        // If no text is entered, set the hidden value of TrademarkId to null and return.
        if (queryValue.length === 0) {
            $("#hdnTrademarkId").val(null);
            return 0;
        }

        // If the entered text is the last chosen text, no need to search again.
        if (lastTrademarkNameChosen === queryValue) {
            return 0;
        }

        // Set the trademarkId to null as the entered text, doesn't match anything.
        $("#hdnTrademarkId").val(null);

        var url = "/areaname/controllername/SearchTrademarks";
        var params = { trademarkName: queryValue };

        // Your get method should return a limited set (for example: 10 records) that starts with {{queryValue}}.
        // Return a list (of length 10) of object {id, text}.
        return $.get(url, params, function (data) {
            // Keeps the current displayed items in popup.
            var trademarks = [];

            // Loop through and push to the array.
            $.each(data, function (i, item) {
                var itemToDisplay = item.text;
                trademarksHashMap[itemToDisplay] = item;
                trademarks.push(itemToDisplay);
            });

            // Process the details and the popup will be shown with the limited set of data returned.
            process(trademarks);
        });
    },
    updater: function (itemToDisplay) {

        // The user selectes a value using the mouse, now get the trademark id by the selected text. 
        var selectedTrademarkId = parseInt(trademarksHashMap[itemToDisplay].value);
        $("#hdnTrademarkId").val(selectedTrademarkId);

        // Save the last chosen text to prevent searching if the text not changed.
        lastTrademarkNameChosen = itemToDisplay;

        // return the text to be displayed inside the textbox.
        return itemToDisplay;
    }
  });

});
Suber answered 17/2, 2022 at 9:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.