Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reset a HTML5 "number" field containing text using AngularJS in Google Chrome

Use Case

I have a number field that specifically says "Enter a number". The end user will invariably enter a string. When the user clicks the "Reset" button using Google Chrome, the number fields containing text will not reset.

The requirements are:

  • Users cannot be upgraded to follow instructions. :D
  • Clicking the reset button should default the number back to undefined.
  • Ideally, we'd like to keep the type="number" attribute as it allows for the keypad to popup on mobile devices.

Code

A jsFiddle demo is available.

Angular Template

<div ng-app="app" ng-controller="ctrl">
    <p>
        Enter a string into the "number" field. Clicking any of the buttons
        will not clear the field.
    </p>
    <p>
        Enter a number into the "number" field. Clicking any of the buttons
        will clear the field.
    </p>
    <input type="number" ng-model="someValue" placeholder="Enter a number"/>
    <button type="button" ng-click="set('hello, world!')">Set to Hello, World!</button>
    <button type="button" ng-click="set(undefined)">Set to undefined</button>
    <button type="button" ng-click="set('')">Set to empty string</button>
    <button type="button" ng-click="set(0)">Set to zero</button>
</div>

Angular Application & Controller

angular.module('app', [])
.controller('ctrl', function($scope) {
    $scope.someValue = undefined;
    $scope.set = function(val) {
        $scope.someValue = val;
    };
});

Question

  • How do you reset a number field to undefined (or blank) containing an invalid value within Angular?
like image 284
Pete Avatar asked Nov 02 '22 01:11

Pete


1 Answers

Your field is required, so say it to Angular!

http://jsfiddle.net/TQ59f/10/

<input type="number" ng-model="someValue" required="true" placeholder="Enter a number"/>

Note that setting undefined as your number's value won't clear the number input. However, setting a non-numeric string as a value (like hello world) will clear the field, as it isn't numeric.

Edit: directive way found by poster mister_rampage seems to be the AngularJS way to solve the problem without "required".

like image 64
ngasull Avatar answered Nov 08 '22 05:11

ngasull