简体   繁体   English

替换按键jQuery上的部分输入值?

[英]Replace part of input value on keypress jquery?

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 '/'; 我想实现在输入值大于或等于3时,用'/'替换string [3]的那部分;

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

And here is jquery 这是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. 因此,简而言之,当用户在输入字段中输入例如1234时,数字3需要用'/'代替,并且该值将是12/2017,例如信用卡的到期日。 Thanks in advance 提前致谢

You can try something like this. 您可以尝试这样。 Had to change the maximum length of input's value from 6 to 7. 必须将输入值的最大长度从6更改为7。

Try with eg 12/2017. 尝试使用例如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" /> 

You could try the following. 您可以尝试以下方法。

Where delimeterIndeces is where in the string you want to check and change the values. 在哪里delimeterIndeces是要在字符串中检查和更改值的地方。 InputString is the string returned from the input tag. InputString是从输入标签返回的字符串。

 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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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