I am trying to insert additional characters in a specific string.
function sample(x) {
if (x.value.length > 2 && x.value.length < 5) {
var first = x.value.substring(0, 2) + "'";
var second = x.value.substring(2, x.value.length) + "''";
x.value = first + "" + second ; }
}
<input id="txt" type="text" placeholder="onkeypress" onkeypress="sample(this)" value="" /><br />
<input id="txt1" type="text" placeholder="onchange" onchange="sample(this)" value="" />
By using onchange
attribute in htmlinput, the code runs perfectly. But can this also run with onkeypress
attribute? If value of inputs is 1006, the result should be 10'06''. Help. Thanks.
Try this:
You need to replace the
quotes('/")
before manipulating the string. Also usekeyup
event. Refer this to understand the purpose of each events.onkeyup
is fired when the key is released
function sample(x) {
x.value = x.value.replace(/[\'\"]/g, '');
if (x.value.length > 2 && x.value.length < 5) {
var first = x.value.substring(0, 2) + "'";
var second = x.value.substring(2, x.value.length) + "''";
x.value = first + "" + second;
}
}
<input id="txt" type="text" placeholder="onkeypress" onkeyup="sample(this)" value="" />
<br/>
<input id="txt1" type="text" placeholder="onchange" onchange="sample(this)" value="" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With