user43153 user43153 - 2 months ago 6
Javascript Question

JavaScript replace method stop scrolling to end

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.

Answer

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>

Comments