Search code examples
javascriptjqueryhtmltwitter-bootstraptypehead

typehead disallow free text entry?


I am using bootstrap typeahead in my textbox to bind the list of users through Ajax call here is my code

$("#userMapping_User").typeahead({
    source: function (query, process) {
        return $.get($_GetUsers_ByLoggedInUser, { term: query }, function (result) {

            var resultList = [];
            $.map(result, function (item, id) {
                if (item && (item.first_name || item.last_name)) {
                    var displayName = item.first_name + ' ' + item.last_name;
                    var user = { id: item.UserId, name: displayName ? displayName.trim() + ' - ' + item.email : '' };
                    resultList.push(user);
                }
            });
            return process(resultList);
        });
    },
    minLength: 2,
    autoSelect: true,
    afterSelect: function (e) {
        $("#userMapping_SelectedUserId").val(e.id);
        $("#userMapping_User").removeClass('form-error');
        $(".error-block").remove();
    }
});

But the problem is that I want to disable the free text entry so the user cannot able to enter invalid value only those value is inserted which are available in the list?


Solution

  • Yes, you can do this thing with the below code.

    var myData = [...]; // This array will contain all your possible data for the typeahead
    
    $("#my-type-ahead").typeahead({source : myData})
                       .blur(validateSelection);
    
    function validateSelection() {
        if(source.indexOf($(this).val()) === -1) 
            alert('Error : element not in list!');
    }
    

    This was the answer given by @samuel in this Link. But I suppose you can do better by using callback function and prevent value being entered. Its your choice.

    Cheers..!!