Is there a way to automatically insert dashes (-) into a textbox within an aurelia typescript application?

I'm attempting to create a textbox that will only accept contact numbers in the XXX-XXX-XXXX format, but I am having trouble achieving this. Can anyone provide guidance on how to implement a formatted contact number in typescript aurelia?

textbox.html

<input type="text" name.bind="name" class="form-control" placeholder.bind="placeholder" maxlength.bind="maxlength" onblur="addHyphen(f)"/>

textbox.ts

addHyphen(f){
    f.value = f.value.slice(0,3)+"-"+f.value.slice(3,6)+"-"+f.value.slice(6,10);
   }

Answer №1

I made some updates to the code in order to make it function similarly to the JsFiddle example you provided in the comments.

textbox.html

<template>
  <input type="text" name.bind="name" class="form-control" 
    placeholder.bind="placeholder" maxlength.bind="maxlength
    keydown.delegate="keydown($event)" ref="text"/>
</template>

textbox.ts

export class Textbox {
  public text: HTMLInputElement;

  public keydown(e) {
      const key = e.key || e.keyCode || 0;
      if (key !== 8 && key !== 9) {
          if (this.text.value.length === 3) {
              this.text.value += '-';
              console.log(e);
          }
          if (this.text.value.length === 7) {
              this.text.value += '-';
              console.log(e);
          }
      }
    return (key == 8 || key == 9 || key == 46 || (key >= 48 && key <= 57) || (key >= 96 && key <= 105));
  }
}

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

Is it possible to dynamically assign a template reference variable to a newly created DOM element in TypeScript?

After creating a DOM element with this.document.createElement('h1'), I am looking to insert the element into a section tag using a template reference variable (myTRF), similar to the example below: <section> <h1 #myTRF>This is my he ...

Angular Test Error: Refactoring requires a source file to be present

Trying to execute the command ng test, I encountered an error message. How can this issue be resolved? I am unsure of its meaning. ERROR in Must have a source file to refactor. To eliminate this warning, use "ng config -g cli.warnings.versionMismatc ...

Angula 5 presents a glitch in its functionality where the on click events fail

I have successfully replicated a screenshot in HTML/CSS. You can view the screenshot here: https://i.stack.imgur.com/9ay9W.jpg To demonstrate the functionality of the screenshot, I created a fiddle. In this fiddle, clicking on the "items waiting" text wil ...

Reorganize the data in a different manner (collections of items instead of individual items linked to groups)

Is there a way to create a function that converts data from `DevicesType` to `GroupsType` below? Instead of having a list of devices showing the groups they belong to, I need a list of groups with their respective devices. type DevicesType = { id: string ...

Discover the type of generic keyof in TypeScript

My types implementation is structured as follows: type GenericType<T, K extends keyof T = keyof T> = { name: K; params: T[K] } type Params = { a: 1; b: 2; } const test: GenericType<Params> = { name: "a", params: 2 } ...

Encountering a problem while attempting to update react-router from version 5 to version 6

I am encountering a typescript error after upgrading React-router-dom from v5 to v6. How can I resolve this issue? Below is the code snippet. Thank you in advance. export function withRouter(ui: React.ReactElement) { const history = useNavigate(); con ...

Receive notification indicating that the function is of void type

As a newcomer to angular, I am currently in the process of setting up my authorization module for an ionic project I am developing. I have made significant progress, but I have encountered an issue with the 'auth' service that I created. Within ...

Identifying row expansion in ngx-datatable: detecting expand status on row click

Is there a way to determine if a line has already been expanded when using the toggle feature? When you click on a line, it expands and shows the details. Here is some code in HTML: <ngx-datatable #dataTable ... (select)='onRowSelect($eve ...

The function's return value encompasses various types, and the property does not exist within them

Currently, I am utilizing typescript for developing a NodeJS application. Within this application, I have incorporated a node module known as ts-md5, which contains a function called hashStr() that may return either a string or an Int32Array value. There ...

The type of 'username' cannot be determined without specifying the reference to '@angular/forms/forms' in the node modules

I'm encountering an issue with my application: forgot-password.component.ts(44,7): error TS2742: The inferred type of 'username' cannot be named without a reference to '.../node_modules/@angular/forms/forms'. This is likely not po ...

Setting up subdocuments using Typegoose to initialize models

We recently switched our project from pure Mongoose to Typegoose, and while we are satisfied overall, there is one issue that continues to trouble us. Consider the following simple model: class Animal { @prop() public name?: string; } const AnimalMode ...

Struggling to grasp React class components while working with generics

I'm having trouble understanding how this is supposed to function. I have a parent class with props and an interface for the child class's props. The issue arises with a TypeScript error message: The property 'lineWidth' does not exist ...

Make sure to verify the status of ngmodel or forms to see if they are dirty or contain

In Angular, how can I determine if ngModel or form fields are dirty or have input without using formgroup? I need to check if at least 5 of the input fields have a value or are considered dirty in order to display a message. How can I achieve this for 5 f ...

Create a unique onblur event listener for every element in a loop in Javascript

https://i.sstatic.net/tRYul.png I have added several items to a column in the database, but I am unsure of how to implement an onblur function for validation for each item within a loop. For example, if the NAME field is empty, I want to display an alert ...

Adding text in a key value pair object can be easily achieved by specifying the key

I was able to transform two arrays into a key-value pair object. firstArray: [] = ['a','b','c','d'] secondArray: [] = [1,2,3,4] Below is the code used to accomplish this transformation: let dict = firstArray.map(fun ...

Exploring methods to modify the Discord scopes in the upcoming Auth v5 update

image description placeholder I'm trying to modify the scope, remove the email and include guilds in my project. I searched for a solution but couldn't find one that worked. Can anyone help me figure out how to change the scopes? I attempted to ...

Guide on effectively testing the catch block of a Typescript function using mocha and chai

In my TypeScript class, I have implemented several functions, each containing a try-catch block that returns a predetermined response upon encountering an error. While writing unit tests using Mocha and Chai, I am facing difficulties in intentionally trig ...

The options passed to createReadStream in TypeScript do not accept {start: 90, end: 99}

After updating to TypeScript 1.6.2, I encountered an issue with my call to createReadStream(). The problem arises because the type definition in node.d.ts does not recognize 'start' and 'end' in the options parameter. var st = fs.crea ...

Why Your Custom Validator Might Not Be Displaying Error Messages

Regrettably, I am unable to display the code at this time, so I will provide an explanation instead. The issue I am facing is with a detail view located within an update panel. I have added a custom validator that should display an error message if Radio ...

A guide on arranging array elements in an Angular application to span over multiple rows

Within my Angular application, I have a collection of companies stored in an array within my TypeScript file. These companies are dynamically rendered in the HTML using the ngFor directive as depicted in the following code snippet: <div class="card-dec ...