angularjs force uppercase in textbox

JavascriptAngularjsUppercaseAngularjs Filter

Javascript Problem Overview


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/>

and

<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?

Javascript Solutions


Solution 1 - Javascript

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

this answer is based on the answer here: https://stackoverflow.com/questions/15242592/angular-js-how-to-autocapitalize-an-input-field</a>;.

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

angular
  .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;
            modelCtrl.$setViewValue(capitalized);
            modelCtrl.$render();
            // set back the cursor after rendering
            element[0].selectionStart = selection;
            element[0].selectionEnd = selection;
          }
          return capitalized;
        }
        modelCtrl.$parsers.push(capitalize);
        capitalize(scope[attrs.ngModel]); // capitalize initial value
      }
    };
  });

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

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

Solution 2 - Javascript

The accepted answer causes problems if someone tries to enter a lowercase letter at the beginning of an existing string.. The cursor moves to the end of the string after each key press. Here's a simple solution that addresses all the issues:

directive('uppercased', function() {
    return {
        require: 'ngModel',
        link: function(scope, element, attrs, modelCtrl) {
            modelCtrl.$parsers.push(function(input) {
                return input ? input.toUpperCase() : "";
            });
            element.css("text-transform","uppercase");
        }
    };
})

Here's a fiddle: http://jsfiddle.net/36qp9ekL/1710/

Solution 3 - Javascript

The idea is to show (not transform) the string as uppercase at client side and transform into uppercase at server side (users can always control what happens at client side). So:

  1. in the html:

    here no uppercase transformation.

  2. in the css:

    #test {text-transform: uppercase;} data is shown as uppercase, but actually still lowercase, if user typed in lowercase.

  3. turn the string into uppercase at server side when inserting into database.

= = = = = for playing around, can try follow:

<input type="text" ng-model="test" ng-change="test=test.toUpperCase();">
<input type="text" ng-model="test" ng-blur="test=test.toUpperCase();">

but I think ng-change or ng-blur ways are not necessary for your case.

Solution 4 - Javascript

You cannot make filter on ng-model since it has to be assignable. the workaround is either parser, or simply ng-change.

<input ng-model="some" ng-change="some = (some | uppercase)"  />

This should work.

Solution 5 - Javascript

When used with Bootstrap, just add text-uppercase to input's class attribute.

Solution 6 - Javascript

one of the simple way is,
<input type="text" ng-model="test" ng-change="upper(test)/>

just do below 2 line code in your js file,
$scope.upper = function(test){
$scope.test = test.toUpperCase();
}

here is my fiddle http://jsfiddle.net/mzmmohideen/36qp9ekL/299/

Solution 7 - Javascript

This will not work at all.

ng-model is for specifying which field / property from the scope should be bound to the model. Also, ng-model does not accept an expression as value. Expressions in angular.js are things between {{ and }}.

The uppercase filter could used in the output and everywhere where expressions are allowed.

You cannot do what you want to do, but you could use CSS's text-transform to at least display everything in uppercase.

If you want to have the value of a text field in uppercase letters you can achieve this with some custom JavaScript.

In your controller:

$scope.$watch('test', function(newValue, oldValue) {
  $scope.$apply(function() {
    $scope.test = newValue.toUpperCase();
  }
});

Solution 8 - Javascript

Don't forget to include 'ngSanitize' in your module!

app.directive('capitalize', function() {
	return {
		restrict: 'A', // only activate on element attribute
	    require: '?ngModel',
		link : function(scope, element, attrs, modelCtrl) {
			var capitalize = function(inputValue) {
				if(inputValue) {
					var capitalized = inputValue.toUpperCase();
					if (capitalized !== inputValue) {
						modelCtrl.$setViewValue(capitalized);
						modelCtrl.$render();
					}
					return capitalized;
				}
			};
			modelCtrl.$parsers.push(capitalize);
			capitalize(scope[attrs.ngModel]); // capitalize initial value
		}
	};

});

  • Pay attention to "?" in "require: '?ngModel',"... only then worked my application.

  • "if(inputValue) {...}" For no undefined error occurs

Solution 9 - Javascript

When using bootstrap:

First approach: Using class text-uppercase

<input  type="text" class="text-uppercase" >

Second approach: Using style which can be applied with existing class

<input  type="text" class="form-control" style="text-transform: uppercase;">

Here is my stackBlitz: https://angular-nvd7v6forceuppercase.stackblitz.io

Solution 10 - Javascript

it is just an alternative , you can use this " text- transform : capitalize ; " in your css and the text entry will be capitalized. unless the user types it in capital letters everywhere.

it is just an alternative ^^

Solution 11 - Javascript

To improve the answer by Karl Zilles this is my revision of his solution. In my version the placeholder isn't changed to uppercase and works also if you want to do a regex on the string. It also take the "type" of the input string (null or undefined or empty):

var REGEX = /^[a-z]+$/i;
myApp.directive('cf', function() {
    return {
        require: 'ngModel',
        link: function(scope, elm, attrs, ctrl) {
            ctrl.$validators.cf = function(modelValue, viewValue) {
            ctrl.$parsers.push(function(input) {
                elm.css("text-transform", (input) ? "uppercase" : "");
                return input ? input.toUpperCase() : input;
            });
            return (!(ctrl.$isEmpty(modelValue)) && (REGEX.test(viewValue)));
        }
    }
}
});

Solution 12 - Javascript

Solution with cursor shift fix

.directive('titleCase', function () {
        return {
            restrict: 'A',
            require: 'ngModel',
            link: function (scope, element, attrs, modelCtrl) {
                var titleCase = function (input) {
                    let first = element[0].selectionStart;
                    let last = element[0].selectionEnd;
                    input = input || '';
                    let retInput = input.replace(/\w\S*/g, function (txt) { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); });
                    if (input !== retInput) {
                        modelCtrl.$setViewValue(retInput);
                        attrs.ngModel = retInput;
                        modelCtrl.$render();
                        if (!scope.$$phase) {
                            scope.$apply(); // launch digest;
                        }
                    }
                    element[0].selectionStart = first;
                    element[0].selectionEnd = last;
                    return retInput;
                };
                modelCtrl.$parsers.push(titleCase);
                titleCase(scope[attrs.ngModel]);  // Title case  initial value
            }
        };
    });

Solution 13 - Javascript

If you want to change model and value, use:

angular.module('MyApp').directive('uppercased', function() {
	return {
		require: 'ngModel',
		link: function(scope, element, attrs, ngModel) {
			element.bind("blur change input", function () {
				ngModel.$setViewValue($(this).val().toUpperCase());
				$(this).val($(this).val().toUpperCase());
			});
			element.css("text-transform","uppercase");
		}
	};
});

Then add uppercased to your html input text

<input  type="text" uppercased />

Solution 14 - Javascript

I would just use the filter itself in the controller:

 $filter('uppercase')(this.yourProperty)

just keep in mind that, if you you are going to use it inside a controller, for example, you need to inject this filter:

app.controller('FooController', ['$filter', function($filter) ...

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSamView Question on Stackoverflow
Solution 1 - JavascriptGHCView Answer on Stackoverflow
Solution 2 - JavascriptKaren ZillesView Answer on Stackoverflow
Solution 3 - JavascriptTimathonView Answer on Stackoverflow
Solution 4 - Javascriptqwerty_igorView Answer on Stackoverflow
Solution 5 - JavascriptLudovic GuillaumeView Answer on Stackoverflow
Solution 6 - JavascriptMohideen bin MohammedView Answer on Stackoverflow
Solution 7 - JavascriptTheHippoView Answer on Stackoverflow
Solution 8 - JavascriptDeividView Answer on Stackoverflow
Solution 9 - JavascriptPalash RoyView Answer on Stackoverflow
Solution 10 - Javascriptuser1999385View Answer on Stackoverflow
Solution 11 - JavascriptMatteo GaggianoView Answer on Stackoverflow
Solution 12 - JavascriptAkRoyView Answer on Stackoverflow
Solution 13 - JavascriptSergio MarsilliView Answer on Stackoverflow
Solution 14 - JavascriptraeffrayView Answer on Stackoverflow