Close ui-bootstrap typeahead menu only when a row is manually chosen

I have set up this jsBin to show the problem I am facing. When you visit the link and try to type "Five," the expected behavior would be to type "Five" and then press tab. However, in this case, you need to type "Five" and then either escape or click outside the box without selecting any other options.

Essentially, with typeahead functionality, pressing tab will select the first matching result for your input, which is not the desired behavior. I expect the selected option to exactly match what I am typing, requiring me to down-arrow to choose from the available results.

Below is the code snippet used in the jsBin:

<div ng-controller="TestController">
  <div>
    {{selected}}
  </div>
  <input type="text" ng-model="selected" typeahead="item for item in typeaheadOptions | filter:$viewValue">
</div>

And here is the corresponding JavaScript code:

var app = angular.module('app', ['ui.bootstrap'])

.controller('TestController', function($scope) {
  $scope.typeaheadOptions = [
    'One','Two','Three','Four','Five-Hundred','Fifteen','Fourteen','Fifty','Six','Seven','Eight','Nine','Ten'
  ]
});

Answer №1

After some modifications, I was able to customize ui-bootstrap to suit my needs perfectly.

I introduced a new property/attribute called mustMouseDownToMatch to the directive, as shown below:

<input type="text" ng-model="selected" typeahead="item for item in typeaheadOptions | filter:$viewValue" typeahead-mouse-down-to-match="true">

The corresponding JavaScript code:

var mustMouseDownToMatch = originalScope.$eval(attrs.typeaheadMouseDownToMatch) ? originalScope.$eval(attrs.typeaheadMouseDownToMatch) : false;

In addition, I implemented a function that inserts the current text into the first item of the typeahead list and selects it:

var setFirstResultToViewValue = function (inputValue) {
    scope.matches.splice(0, 0, {
        id: 0,
        label: inputValue,
        model: inputValue
    });

    // select the first item in the list
    scope.activeIdx = 0;
}

This function is invoked within the getMatchesAsync call in the typeahead directive:

var getMatchesAsync = function(inputValue) {
// perform necessary actions
    $q.when(parserResult.source(originalScope, locals)).then(function(matches) {
        // check conditions
        if (matches.length > 0) {
             // perform tasks
        }
        if (mustMouseDownToMatch) {
            setFirstResultToViewValue(inputValue);
        }
        // continue operations
  };

Answer №2

After encountering a similar issue, I discovered a more recent solution that may not have been available previously. https://i.stack.imgur.com/LqOZr.png

You can now include this as an attribute

typeahead-should-select="$ctrl.typeaheadShouldSelect($event)"

Add the following code to your controller or custom component to enable tab navigation and press enter to make a selection.

 self.typeaheadShouldSelect = function($event) {
                if ($event.key === 'Tab') {
                    var e = $.Event('keydown');
                    e.which = 40;
                    $($event.currentTarget).trigger(e);
                }
                if ($event.key === 'Enter') {
                    return true;
                }
            }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Searching for the element that triggered the event using jQuery or JavaScript

Can anyone offer tips on how to use console.log to identify the element that triggered a hover event? I'm trying to debug an issue specifically on iOS. I'm not looking to locate the specific item that the action was performed on, but rather what ...

Managing the ERR_NAME_NOT_RESOLVED issue

Currently, I am facing a task related to the health check endpoint where I need to receive a response from the backend or encounter a net::ERR_NAME_NOT_RESOLVED error if we are outside of a specific network. When attempting to send a request to my endpoin ...

The dynamic scope variable in AngularJS is failing to update after a successful HTTP POST request

Struggling with retrieving data from a database and assigning it to a dynamic scope variable using a function. The issue lies in the fact that the data is not being assigned to the variable on the first attempt. Can anyone offer assistance? Here's th ...

Transforming ASP.NET MVC IEnumerable view model into a JSON array of elements

My goal is to develop a dynamic calendar in ASP.NET MVC that pulls event data from a database to populate it. Right now, the calendar is set up to read a json array of objects, but I am facing an issue with converting my ViewModel data into a format that t ...

Transforming the text to be "unreadable"

I find myself in a rather odd predicament where I must display my name and contact details on a webpage. Although I am comfortable with sharing this information, I would prefer that it remain unreadable to robots or other unauthorized sources. Essentially ...

Use JavaScript to retrieve a value and display it on a PHP page

I am trying to create a system that can generate and deliver JSON data. Here is the PHP code I have so far: <?php header("Content-Type:application/json"); require "data.php"; if(!empty($_GET['name'])) { $name=$_GET['name']; ...

Tips for making sure a header is consistently at the top of every page during printing

I need help with my website - I have a table that is quite tall and spans across multiple pages when printing. Is there a way to make the header row appear on top of each page when printing? ...

Include an extra hyperlink in the adaptive menu bar

I have successfully created a responsive Navigation bar. Now, I would like to add an "Account" link on the right side of the navigation. My initial thought was to insert a div into a ul element, but I realize that this may not be W3C compliant. <div c ...

Using Ionic with Ubuntu to easily connect to MySQL and PHPMyAdmin

element, My current project involves creating a mobile app using Ionic on Ubuntu. I have successfully installed and configured phpmyadmin, which is now operational at http://localhost/phpmyadmin. Can someone guide me on how to configure Ionic to connect ...

What is the best way to implement validation in a textarea to restrict the word count to a minimum of 250 and a maximum

I want to implement jQuery validation for a textarea field, with a requirement of 250 minimum words and 1000 maximum words. Additionally, I need to display the word count in a span tag next to the text area. How can I ensure that this validation works even ...

Tips for transmitting form information in a fetch call

As I was developing a nodejs server, I encountered an issue with the POST call that involves sending form input data to a remote server. Despite everything else working fine, the form data was not being received by the server. Below is the code snippet in ...

Best Practices for Handling Pre-State Setting Mutations in Flux Design Pattern

Currently, I am developing a Vue application utilizing Vuex and following the Flux design pattern. I have encountered what seems to be an inefficient practice of duplicating code in small increments. I am hopeful that this is just a misunderstanding on my ...

Using JavaScript to create a tree structure with hierarchical organization in JSON

Having some trouble converting a nested hierarchical tree from a JSON array. Looking to create a hierarchical tree structure from the provided JSON data. Below is the data: [{ "_id" : "59b65ee33af7a11a3e3486c2", "C_TITLE" : "Sweet and Snacks", ...

Displaying/Concealing specific choices using jQuery

Greetings! I am in need of some assistance with my coding query. I have been working on a piece of code where selecting 'x' should reveal another dropdown, which seems to be functioning correctly. However, if I navigate three dropdowns deep and t ...

JavaScript can be used to deactivate the onclick attribute

Is there a way to deactivate one onclick event once the other has been activated? Both divs are initially hidden in the CSS. I'm new to programming, so any help is appreciated. Markup <a id="leftbutton" href="#" onclick="showDiv(this.id); return ...

Using Typeof in an IF statement is successful, but attempting to use ELSE with the same

My goal is to create a JavaScript variable called str. In case the ID idofnet doesn't exist, I would like to prompt the user for a value to assign to str. However, if idofnet does exist, then I want to retrieve its value and assign it to str. This is ...

Issue with Angular-cli: typescript files not being generated when using the --dev option

Currently using angular-cli version 1.0.0-beta.14 with node version 6.6.0 on a Windows 32 bit x64 operating system. This setup utilizes the webpack version of angular-cli and I can successfully use ng build to compile. The output of ng build indicates that ...

The deployment on heroku encountered an error during the build process

I'm attempting to deploy my React application on Heroku, but I keep encountering the following errors: -----> Installing dependencies Installing node modules npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ...

How can I show the text name as a selection in the React Material UI Autocomplete component while sending the ID as the value?

Material UI Autocomplete component functions properly, but I am interested in extracting object.id as the value for the onSelect event (rather than object.name). Essentially, I want to display the object.name as the select item label, while retrieving obje ...

Django: Error - < found where unexpected

Using a combination of Django and jQuery, I have implemented a file upload feature with AJAX. Everything seems to be working correctly - the files are successfully uploaded, reflected in the database, and stored on the server. However, upon completion of t ...