-1

I need to format an input text like this: 2342452-1. After typing seven numbers I need to add a dash (-) and then a number again. Is there a simple way of doing this in javaScript?

2
  • Yes, using either a search engine like Google or the search field from SO (: Commented Sep 23, 2018 at 1:07
  • Take a look at input-mask, this helps me a lot on putting masks in input fields. Commented Sep 23, 2018 at 1:10

1 Answer 1

1

You can check the length and use indexOf to find if this string contains a '-'

function maskinput(e) {
  if (e.target.value.length > 7 && e.target.value.indexOf('-') === -1) {
    let substring1 = e.target.value.slice(0, 7),
      substring2 = e.target.value.slice(7, e.target.value.length);
    e.target.value = substring1 + '-' + substring2;
  }
}
<input type='text' onkeyup='maskinput(event)'>

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.