0

I tried to make translator using JavaScript replace method and it is working fine. My question is how to stop scroll to end on text box because when I type something in the text box it will replace and the cursor will go to the end of word. Therefore I can't replace or type in between some words.

HTML Code:

<form name="inputform">
<input class="Search" type="text" autofocus name="searchbox" onKeyUp="transcrire()" id="Search">
</form>

JavaScript Code:

var inp;
function transcrire() {
inp = document.inputform.searchbox.value; 
inp = inp.replace(/a/g, "B");
inp = inp.replace(/i/g, "D");
document.inputform.searchbox.value=inp;
}

When I typed "a" on text box, it will replace to "B". When I typed "i" on text box, it will replace to "D". If you can please give me answer in JavaScript and JQuery. Only can use this text box no other button or something.

depperm
  • 10,606
  • 4
  • 43
  • 67
user43153
  • 139
  • 6

3 Answers3

0

Heres an example I got from this SO post:Set keyboard caret position in html textbox

function setCaretPosition(elemId, caretPos) {
    var elem = document.getElementById(elemId);

    if(elem != null) {
        if(elem.createTextRange) {
            var range = elem.createTextRange();
            range.move('character', caretPos);
            range.select();
        }
        else {
            if(elem.selectionStart) {
                elem.focus();
                elem.setSelectionRange(caretPos, caretPos);
            }
            else
                elem.focus();
        }
    }
}
Community
  • 1
  • 1
The Dembinski
  • 1,469
  • 1
  • 15
  • 24
0

var inp;
$('#Search').on('keyup',function(e){
  inp = $(this).val(); 
  inp = inp.replace(/a/g, "B");
  inp = inp.replace(/i/g, "D");
  $(this).val(inp);
  $(this).get(0).setSelectionRange(0, 0);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="inputform">
<input class="Search" type="text" autofocus name="searchbox"  id="Search">
</form>
  • 1
    This code cursor go to start of text box. I don't want it. For example if I typed BBBDDD and again I will type "a" in between BBB"a"DDD. therefore result will be BBBBDDD and cursor should be in BBBB_DDD. – user43153 Sep 29 '16 at 16:40
0

Simply get the initial target position and set the position back to where it was after replacing with regex.

var inp;
$('#Search').on('keyup',function(e){
  var target = e.target,
  position = target.selectionStart;

  inp = $(this).val(); 
  inp = inp.replace(/a/g, "B");
  inp = inp.replace(/i/g, "D");
  $(this).val(inp);
  $(this).get(0).setSelectionRange(position, position );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="inputform">
  <input class="Search" type="text" autofocus name="searchbox" id="Search">
</form>
depperm
  • 10,606
  • 4
  • 43
  • 67