0

I have two inputs when you type the upper one it writes the bottom one same time. I have a letter i and its different from letter ı but in English they have same capital letter I so I wrote the following code to address this:

$(".buyuk").on("keypress", function(event) {
    event.preventDefault();
    if (event.which == 105)
        $(this).val($(this).val() + "İ");
    else
        $(this).val($(this).val() + String.fromCharCode(event.which).toUpperCase());
});

After you write the word when you want to edit the word from middle it adds the letter to end. For example, I typed moitor but when though I expected the output to be monitor, it became moitorn instead.

Huey
  • 5,110
  • 6
  • 32
  • 44
Seuphoria
  • 17
  • 7
  • 2
    `I have two inputs` Where is your second input in your code example? Can you create a fiddle of this? – Mivaweb Jun 29 '15 at 14:42
  • Same page next to other one. @Mivaweb – Seuphoria Jun 29 '15 at 14:43
  • I agree with @Mivaweb, as it stands it's unclear what you're talking about. Perhaps you could include a JSFiddle or add a code snippet to illustrate the issue. – Huey Jun 29 '15 at 14:44
  • when you click between "mo"and "itor" and type "n" it does not become "monitor" it becomes "moitorn" – Seuphoria Jun 29 '15 at 14:46

2 Answers2

0

What you need, is to know where the active caret position is. I found a nice function here.

With that function, you can rewrite your function:

$(".buyuk").on("keypress", function(event) {
    event.preventDefault();
    if (event.which == 105)
       var key = "İ";
    else
       var key = String.fromCharCode(event.which).toUpperCase();    
    var carPos = $(this).getCursorPosition();
    var v = $(this).val();
    var l = v.length + 1;
    var newValue = v.substr(0,carPos) + key + v.substr(carPos,l)
    $(this).val( newValue );
});

DEMO

Note

Community
  • 1
  • 1
GreyRoofPigeon
  • 17,833
  • 4
  • 36
  • 59
  • @Dave Chen's answer solved the problem and when I tried your code I can not write between letters in second input. – Seuphoria Jun 29 '15 at 15:26
0

Try this:

$(".buyuk").on("keypress", function(event) {
  event.preventDefault();

  var char = String.fromCharCode(event.which).toUpperCase();
  if (event.which == 105) char = "İ";

  var og = $(this).val();
  var selection = this.selectionStart;

  $(this).val(og.substr(0, selection) + char + og.substr(this.selectionEnd, og.length));

  this.selectionStart = this.selectionEnd = selection + 1;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="buyuk">

This works with select replacement, and doesn't move your cursor position around. So if you type 12345 and select 34 and type J, it will become 12J5, just like a normal text field. It also keeps your cursor position, so if you starting typing in the middle of the input, it doesn't move your cursor to the end of the text field.

Dave Chen
  • 10,887
  • 8
  • 39
  • 67