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

Executing a function within a ng-repeat iteration

Is there a way to call a method within an ng-repeat loop, even if the element does not exist at that moment? I'm facing this issue and I'm not sure how to resolve it... The ID seems to be correct. Strangely, when I run it in the console after ev ...

The Angular integration with Semantic UI dropdown does not display the selected value clearly

I have put together a small example to demonstrate the issue. http://plnkr.co/edit/py9T0g2aGhTXFnjvlCLF Essentially, the HTML structure is as follows: <div data-ng-app="app" data-ng-controller="main"> <select class="ui dropdown" id="ddlStat ...

Passing data retrieved from fetch requests in ReactJS using context: Best practices

Just started learning React and need some help. I'm trying to pass variables with json data to a component for further use but running into errors. What changes should I make to use variables with json data from Store.js in the product.js component? T ...

Transforming an array in JavaScript into a JSON object

I'm currently working on creating a loop in JavaScript or jQuery to generate a new JSON object from an array. The goal is to convert an input JavaScript array into a desired format for the output. Here's the input array: INPUT: [ { ...

Enhancing Vue Filtered Lists for Increased Dynamism

Currently, I am iterating through a list of items using the v-for directive. Before displaying the list, I apply a filter based on a specific value using the .filter() method. To switch between different filtered values, I utilize the v-on:click event. How ...

Issue arises when attempting to submit multiple form fields with identical 'name' attributes, preventing the fields from being posted

Currently, I am facing a challenge with old HTML/JavaScript code. Some parts I have control over, while others are generated from an external source that I cannot manage. There is a form created dynamically with hidden fields. The form is produced using a ...

Can you tell me the JavaScript alternative to Jquery's .load() shortcut method?

Exploring the modernized version of jquery, specifically the .load() ajax shorthand method that is not deprecated. One example to consider is finding the javascript equivalent for the traditional jquery ajax shorthand method mentioned below: $("#targetdi ...

Transferring the dirty state of the view to the parent form

Within my main form's markup, there is a specific structure that includes a tabset and a selectView method in the controller: <tabset vertical="true" type="pills"> <tab ng-repeat="tab in tabsViews" sele ...

Is it beneficial to create a separate component for React form elements?

I've come across advice that suggests when unsure, turning an element into a component is a good idea. But what are the actual benefits of converting form elements like <input /> into components? Let's consider the following example: cons ...

What is the best method for dividing a user interface into several arrays of keys, each grouped by type?

Given a simple structure: structure IPerson { firstName: string; lastName: string; age: number; city: string; favoriteNumber: number; isMarried: boolean; hasDriverLicense: boolean; } How do I create arrays containing keys grouped by data typ ...

Establishing Node.js environment variables when invoking `npm run` command

package.json { "scripts": { "start": "NODE_ENV=development node ./index.js" } } If we wanted to pass and override NODE_ENV when running npm run start, is it possible? npm run start NODE_ENV=production ...

Efficiently updating database records without the need for page reloads using EJS

I'm working on a project that resembles the comment section on Reddit. Users can leave comments and others can reply to those comments. My tech stack includes Node, Express, MySQL, and EJS. The issue I'm facing is implementing the upvote/downvo ...

Solving the issue of image paths within external SCSS files in Nuxt.js

Trying to organize my component scss files separately from their Vue components has been a bit challenging. I also have a GLOBAL scss file that is not scoped, but no matter which approach I take, I can't seem to get the image paths in /assets or /stat ...

Oops! Looks like there's a problem with the helper called "if_equal" in Handlebars

I attempted to incorporate handlebars into my express node application, but it appears to be malfunctioning. const express = require('express'); const hbs = require('hbs'); const expressHbs = require('express-handlebars'); c ...

Determining the Right Version of a Framework in npm: A Guide

One common issue I encounter is the uncertainty of which versions of npm, Ionic, and other tools I should have installed. It often goes like this: "Oh, there's a new version of the Ionic CLI out. Let's update." I install CLI v3.9.0. ...

The functionality of Angular routing fails when it is placed in a separate file

I currently have the following set of files: index.html <html ng-app="gitHubViewer"> <head> <script data-require="angular.js@*" data-semver="1.4.0-beta.6" src="https://code.angularjs.org/1.4.0-beta.6/angular.js"></script> < ...

What is the reason for the delay in the firing of this document.ready event

Similar Question: Understanding window.onload vs document.ready in jQuery I seem to be encountering a problem: I have an image on my webpage that is relatively small. I also have a JavaScript function that dynamically sets the height of the left sideb ...

Generating a dynamic list by utilizing database data once a button has been clicked

I'm looking to create a feature on my website where clicking on a button will populate a paragraph below it with data retrieved from a database query containing two columns. The first column provides the text for a list, while the second column contai ...

Ensure the CSS class stays on Quill clipboard.dangerouslyPasteHTML

One of the challenges I face with using the Quill Text Editor is that when I use the method clipboard.dangerouslyPasteHTML to paste HTML into the editor, it does not maintain custom CSS classes. For example: let content= '<p class="perso-clas ...

Using jQuery to replace the value of a button with a variable string that has been concatenated

I am facing a dilemma with a button on my webpage. The value displayed on the button is a combination of variables and strings, like so: $('#btn1').attr('value','question'+currid+'ans1').button('refresh'); ...