Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Characters inserting in wrong index of the string

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.

like image 553
eirishainjel Avatar asked Oct 07 '15 07:10

eirishainjel


1 Answers

Try this:

You need to replace the quotes('/") before manipulating the string. Also use keyup 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="" />
like image 100
Rayon Avatar answered Sep 19 '22 00:09

Rayon