1

For example I have, input type with predefined length. I want to achieve, when the input value is bigger or equal to 3, to replace that part of string[3] with '/';

<input type="text" id="number" maxlength="6" placeholder="MM/YY"/>

And here is jquery

$('#number').on('keypress',function(){
if(this.value.length <= 3) {
this.value.replace(this.value[3],'/');  
}
});

So in short when user types inside input field for example: 1234, the number 3 needs to be replaced with '/' and than the value would be 12/2017, like expiration date of credit card. Thanks in advance

2 Answers 2

4

You can try something like this. Had to change the maximum length of input's value from 6 to 7.

Try with e.g. 12/2017.

$('#number').on('keypress', function() {
  if (this.value.length >= 2) {
    this.value = this.value.slice(0, 2) + '/' + this.value.slice(3, this.value.length)
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="number" maxlength="7" placeholder="MM/YY" />

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

2 Comments

Awesome Thanks :)
One small issue is that if a user types "12/", they end up with "12//". It might be good to test the value for "/" before doing the replacement.
0

You could try the following.

Where delimeterIndeces is where in the string you want to check and change the values. InputString is the string returned from the input tag.

let delimeterIndices = [2,5]; // "02[/]15[/]2017";
let inputString = "123152017";
let resultString = inputString.split('').map((char, index) => {
  if(delimeterIndices.indexOf(index) !== -1) {
    return '/';
  } else {
    return char;
  }
}).join('');

console.log(resultString);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.