As the user types, automatically format the input field for a seamless and intuitive experience

My current application is running on Angular 1.3.10

I have implemented a jQuery function to automatically add a backslash to the expiration input field once the user types the third number. Although it was a quick fix, I now aim to move this functionality into $scope. However, despite my efforts, I am facing difficulties in doing so and would greatly appreciate any help from those more knowledgeable than me.

Here is the jQuery code that needs to be moved to Angular $scope:

$(document).ready(function () {
    $("#cc-exp").keypress(function () {
        if ($(this).val().length == 2) {
            $(this).val($(this).val() + "/");
        }
    });
});

The expiration html input field:

<md-input-container>
    <label>Expiration MM/YY</label>
    <input ng-model="expiration" id="cc-exp" ng-pattern="/^\d{2}\/\d{2}$/"  name="expiration" type="tel" class="long cc-exp" minlength="5" maxlength="5" required>
    <div ng-messages="payment.expiration.$error" ng-if="payment.$submitted" class="validation-error-display">
       <div ng-message="required">Please enter an expiration date.</div>
       <div ng-message="pattern">Must contain numbers only.</div>
       <div ng-message="minlength">Must be MM/YY format.</div>
       <div ng-message="maxlength">Must be MM/YY format.</div>
    </div>
</md-input-container>

Answer №1

Have you thought about utilizing the $scope.$watch function? This function will trigger each time the expiration changes:

$scope.$watch('expiration',function(newValue, oldValue){
      if(newValue.length == 2) $scope.expiration = $scope.expiration +'/';
});

https://docs.angularjs.org/api/ng/type/$rootScope.Scope

Answer №2

A good approach would be to utilize a directive

Code Snippet

<input ng-model="expiration" id="cc-exp" ng-pattern="/^\d{2}\/\d{2}$/"  name="expiration" 
my-dir type="tel" class="long cc-exp" minlength="5" maxlength="5" required>

Custom Directive Implementation

app.directive('myDir', function() {
    return {
        restrict: 'AE',
        require: 'ngModel',
        link: function(scope, element, attrs, ngModel) {
            element.on('keypress', function(e) {
                var val = ngModel.$viewValue;
                if (val.length == 2) {
                    scope.$apply(function() {
                        ngModel.$setViewValue(val + "/");
                    });
                }
            });
        }
    }
})

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

Transform HTML into PNG with Canvas2image, followed by the conversion of PNG into BMP

Is there a direct way to convert HTML to BMP? After searching online, it seems that there isn't a straightforward method. So, I decided to convert HTML to PNG using canvas JS and then use PHP to convert the file from PNG to BMP. I have a question abou ...

What is the best way to send the totalAmount data from one child component to its parent, and then pass it on to another

I am facing an issue with passing the totalAmount data from cart.js to the parent component (app.js) and then further to another child component (info.js). Despite my attempts, it seems like I am unable to pass it correctly as I encounter the following err ...

Utilizing ng-repeat $index for locating an element within an array

Within my $scope, there is a property called $scope.cars, which is an array of cars. Users have the ability to delete a car from this array. When calling the delete function deleteThis, I pass the $index parameter created by ng-repeat. However, in the Ja ...

What is the best way to pass a Python string to a JavaScript script?

I attempted to utilize the JSON module for this task, but encountered errors in both my JavaScript script and Firebug. For example, I have a line that looks like this: {"fruit":{"apple":100}} When trying to send this to a JavaScript script called jquery. ...

Troubleshooting issues with sending POST requests in node.js

I've been attempting to initiate a post request, but for some reason, it's not going through. Strangely, I'm not seeing any output in the console log of my browser. My node server.js is up and running on x.x.x.x:8000. I've connected it ...

Is it possible to remove individual items from a FlatList by clicking on them and updating the state?

I have a FlatList displaying items from an array called data. My goal is to remove each item individually by clicking on it, but currently when I click on one item, all items are deleted at once. Any suggestions on how to address this issue? Here's ...

How can I automatically center a Vimeo iframe vertically without having to manually adjust the position?

I'm trying to adjust a popular fluid jQuery script so that it can automatically center a vimeo video vertically, without any black bars. A little horizontal cropping is acceptable. Here is my current code: HTML <div class="container"> < ...

How to verify CSRF protection on Node.js/Express endpoints

I have added csrf (cross-site request forgery) protection to my express application like this: ... app.use(express.csrf()); app.use(function (req, res, next) { res.cookie('XSRF-TOKEN', req.csrfToken()); next(); }); ... Everything is working ...

"Enhance Your Website with Dynamic Text Effects using JavaScript

Is there a way to continuously animate text during the loading process of an AJAX request? I've tried implementing various methods, such as using a setTimeout function or an infinite loop, but nothing seems to work for repeating the animation once it& ...

Why is my ASP.NET action returning a 404 error with Angular's $http.get method?

Below is the AngularJS code that I am using: $http.get("/Home/GetEmails").then(function (response) { $scope.emails = response.data; $scope.init($scope.emails); $scope.totalEmails = $scope.emails.length; }); W ...

Passing Parameters to Razor Pages Controller

Within my controller, there exists a function as follows: public ActionResult AddSubSub(int? idOfSubsub) { return RedirectToAction("Index", new { searchword = "" }); } I am able to invoke this function without providing any parameter. I attempted the ...

When render returns another component, React does not invoke componentWillMount

Here is my code setup: const Dashboard = React.createClass({ getInitialState(){ return { user: JSON.parse(localStorage.getItem('user')) }; }, componentWillMount(){ var self = this; $.get({ url: 'http://127 ...

npm encounters difficulty in initiating the server

I encountered some errors after running npm start in my angular project directory. It was working fine yesterday, but today when I entered the npm start command in my cmd prompt, it started showing errors: This is how my package.json file looks like: { ...

Troubleshooting Jasmine Unit Testing issues with the ng-select library

Recently, I integrated the ng-select component from Github into my Angular application without encountering any console errors during runtime. It functions as expected; however, issues arise when running unit tests with Jasmine. To incorporate NgSelectMod ...

What is the reason for receiving the "Must provide query string" error when using the fetch API, but not when using cURL or Postman?

I've been attempting to integrate the graphbrainz library into a React app using the fetch API. No matter how I structure my request body, I keep encountering this error: BadRequestError: Must provide query string. at graphqlMiddleware (C:\U ...

Is it possible to implement formvalidation.io in a React project that is using Materialize-css?

Can the formvalidation.io plugin be used with React and Materialize-css in a project? My project consists of multiple input components that may or may not be within a form. I want to utilize formvalidation for input validation. However, I am unable to find ...

Ways to transfer ID to a different HTML page

I have some Javascript code in a file named nextPage.js. When this code is executed by clicking on something, it should transfer the value of category_id to another page called reportlist.html. Can you please provide assistance with this? var base_url = " ...

Utilizing ng-model on a pair of inputs to achieve synchronized values

Is it possible to use ng-model on an input field that receives a value from another input field? I'm having issues with my code and I can't figure out why. Can ng-model be set to an input field using Angular values? Here's my code: ...

I'm struggling to solve a straightforward jQuery sliding issue

I am struggling to make text slide from right to left on my website. I want the text to appear only when the page loads or refreshes, and then slide off when a link is clicked, revealing new text. Can anyone help me figure this out? http://jsfiddle.net/XA ...

Is there a way to display a secondary header once the page is scrolled down 60 pixels?

.nav-header2{ background: purple; display: flex; justify-content: center; align-items: center; } .header2-container{ width: 68vw; height: 60px; padding: 0 2vh; border: 1px solid red; ...