简体   繁体   中英

I want to automatically add dashes (-) in a textbox. How can I do this in an aurelia typescript application?

Here I am trying to create a textbox which will allow a contact number in the XXX-XXX-XXXX format. But I am unable to create this. How can I create 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);
   }

I updated this so that it works similar to the JsFiddle 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));
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM