Concentrate on the text input once an option is chosen from the select box within AngularJS

I am attempting to focus on an input type text after selecting an option from a select box. However, after selecting the option, the focus switches back to the select box instead of staying on the input.

To see the issue in action, here is a link to a JSFiddle.

Below is the code snippet:

    <div ng-controller="MyCtrl" layout layout-align="center center">
        <md-select ng-model="myModel" placeholder="Pick" ng-change="onChange()" md-on-open="onOpen()">
            <md-option value="0">Zero</md-option>
            <md-option value="1">One</md-option>
        </md-select>

        <input type="text" id="fc">
    </div>
<script>
    angular.module('MyApp', ['ngMaterial'])
    .controller('MyCtrl', function ($scope) {
        $scope.onChange = function() {
            document.getElementById('fc').focus();
        };

        $scope.onOpen = function() {
           document.getElementById('fc').focus();
        };
    })
</script>

Answer №1

According to the comments, it appears that there may be a bug with angular-material causing this issue. It seems to work fine with a standard select instead. Maybe consider creating a github issue.

In the meantime, you can implement a temporary workaround to resolve the problem by attaching a directive to manually focus on the input (using $timeout) when the select is changed.

Directive: Make sure to set a considerable timeout (works with 250ms):

.directive('focus', function($timeout) {
   return function(scope, elem, attr) {
      scope.$on(attr.focus, function(e) {
        $timeout(function() {        
          elem[0].focus();         
        }, 250);
      });
   };
})

Controller: Trigger an event when the select is changed.

$scope.onChange = function() {
   $scope.$broadcast('selectChanged');
};

View: Apply the focus directive to your input element:

<input type="text" id="fc" focus="selectChanged"> 

I have forked your jsfiddle. Now you can check it out and see the solution in action here.

Hopefully, this information proves helpful.

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

Is there a way to retrieve the default ObjectId generated by MongoDB when using NextAuth?

Is it possible to access the MongoDB ObjectId of the user currently logged in when using Next Auth with services like Twitter? When signing in, Next Auth creates a new user, account, and session, but I'm unable to retrieve the _id value for my server ...

I encounter an error message stating "The requested resource has been deleted" whenever another website links to my site

Having recently started working with Angular and Azure setups, I am facing an issue with a simple jade login form that posts to a URL (different origin than my website) upon submission. As a security measure, I have replaced the actual URL with a sample on ...

Creating crypto.createCipheriv arguments from fixed origins

Currently, I am implementing a code snippet in my node.js application to perform string encryption. I am seeking guidance on how to create the KEY and HMAC_KEY from a predetermined source. At the moment, these keys are randomly generated within the progra ...

Chrome is known for its seamless integration with PDFs,

<div align="justify" style="height: 500px; border: 1px solid #ccc; overflow: auto;"> <object data="/policy/download/#zoom=65,65,720" type="application/pdf" width="100%" height="500"></object> </d ...

When attempting to call iFrame in JavaScript, it may not be recognized and result

At the moment, I am in the process of developing my personal portfolio and have come across a perplexing issue that has left me stumped. The structure of my webpage operates on a main-frame structure, which means that instead of navigating through separate ...

What is the process of specifying that an Angular directive must act as a child directive within a particular directive in Angular?

I am currently developing a directive for AngularJS. How can I specifically configure it to require being a child of directiveA? For instance, consider the following example: <my-modal> <m-header>Header</m-header> </my-modal> ...

Performing AJAX callback function on success in jQuery

I've been trying to troubleshoot an error but none of the solutions I've found so far seem to be working for me. I have an ajax request set up to retrieve JSON data from the server. I can see the JSON data that I want to capture when using consol ...

My controller is playing hide and seek with Ionic and it seems

I have been working on integrating a side menu into my app, which required me to make changes to how the controllers are set up. I introduced a menu controller, but now I keep encountering this error message: Argument 'MenuCtrl' is not a functio ...

In JavaScript, define a class with a property that shares the same data type

I am facing a scenario where I need to define a property within a class that is an instance of the same class. Here's an example: class Example { constructor() { this.property = new Example(); } } const e = new Example(); However, I keep ...

I'm searching for the Jasmine framework function definitions specifically for Protractor. Where can I find them?

Are resources available for obtaining support documents or guidelines in order to create a custom framework similar to Jasmine for Protractor? ...

Show the contents of a JSON file using Vue

I have a JSON file containing some data that needs to be fetched and displayed in a component. In the actions of my Vuex store, I've implemented: async getTodos (context) { const todos = [] const response = await fetch('../../data/todos.jso ...

AngularJS has separated the $http service into its own distinct file for easier organization

I am facing an issue with separating the $http GET request for a dictionary from the controller into a separate file as a service. I have searched for solutions, but haven't come across any suitable hints. Please provide me with some guidance. Below ...

Can someone show me the JavaScript code to split a string at every instance of ' '?

Hey there! I have a question about manipulating strings. Take a look at this example: var string = '"In Another World" "Magic Books"' I want to create an array that contains every name within the [""]. How can I ach ...

Updating an array in Vue.js without the need to reload all the data

Recently delving into Vue.js and JavaScript, I'm seeking guidance on updating an array (on Add/Edit/Delete) without having to reload all the data. The goal is to load all data only when initially opening the page with Addresses. Take a look at my cod ...

Creating a Bar Chart in d3js with time on the x-axis and one or multiple sets of numerical data on the y-axis: a step-by

My webpage structure is as follows: <!DOCTYPE html> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <link href="css/style.css" rel="stylesheet" /> &l ...

Using custom icons in JsTree with the Json_data plugin

I have been working on implementing a JsTree in my MVC website and using the json_data plugin to populate the tree. My Controller action returns a JsonResult that uses a custom class to represent the nodes. I have been going through the documentation tryin ...

Mobile WEBSITE Development with Ionic Framework

Exploring the potential of utilizing the Ionic Framework for my mobile website has piqued my curiosity. Are there any concerns I should be aware of when running Ionic Framework on mobile browsers? My plan is to leverage the framework's CSS and JS capa ...

Next.js dynamic pages do not have link functionality to regular pages

I have been working on a web site using next.js, and I've implemented dynamic routing in a folder called pages/artists/[slug].js. It's been working perfectly for the dynamic content, but I'm facing an issue with standard pages like Home, Abo ...

The Katura video is loading properly, yet it is rotating instead of playing

I am working on a web application that involves playing videos from Kaltura platform and then loading the link on an iOS webview. <html> <body> <div id="myEmbedTarget" style="width:400px;height:330px;"></div> ...

Replacing an existing pie chart with a new one using JavaScript

I created pie charts using chartjs V2.6.0, and everything was working fine until I encountered an issue. Whenever I input new data into the same chart, it keeps displaying the previous data when hovering over. I attempted to fix this by using the $('# ...