angularjs force uppercase in textbox


I’ve tried using the uppercase filter but it does not work. I’ve tried doing it two ways:

<input type="text" ng-model="test" uppercase/>


<input type="text" ng-model="{{test | uppercase}}"/>

The 2nd triggers a javascript error:

Syntax Error: Token ‘test’ is unexpected, expecting [:]

I want the text to be forced to uppercase as the user types in the textbox.

How can I do that?


Please see the other answer below, which is superior to this one.

this answer is based on the answer here: How to autocapitalize the first character in an input field in AngularJS?.

I’d imagine that what you’d want would be a parser function like this:

  .module('myApp', [])
  .directive('capitalize', function() {
    return {
      require: 'ngModel',
      link: function(scope, element, attrs, modelCtrl) {
        var capitalize = function(inputValue) {
          if (inputValue == undefined) inputValue = '';
          var capitalized = inputValue.toUpperCase();
          if (capitalized !== inputValue) {
            // see where the cursor is before the update so that we can set it back
            var selection = element[0].selectionStart;
            // set back the cursor after rendering
            element[0].selectionStart = selection;
            element[0].selectionEnd = selection;
          return capitalized;
        capitalize(scope[attrs.ngModel]); // capitalize initial value
<script src=""></script>

<div ng-app="myApp">
  <input type="text" ng-model="name" capitalize>

Answered By – GHC

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published