0

I have my own jquery keyboard that allow users to enter text into a textbox when each key is clicked. The problem is that the user cannot write in a specific position inside the word because of my current code:

HTML:

<input type="text" id="id">

<!--Some keys-->
<div id="k-e" class="key key-btn">e</div>
<div id="k-r" class="key key-btn">r</div>
<div id="k-t" class="key key-btn">t</div>

Jquery:

$("div.key").click(function(e){
    var currentName = $("#name").val();
    $("#name").val(currentName + $(this).text());
});

Right now, for example: If a user click before the letter "i" in "Maia" to write the letter "r", when the key is clicked the letter is entered, but at the end of the word.

Can someone please explain me how can I achieve this with jquery?

Oscar Otero
  • 325
  • 3
  • 11

1 Answers1

1

I had success using JavaScripts selectionStart to find the current cursor position in the input.
Then, I insert the new text at the cursor position by using the method by jAndy found here.

$("div.key").click(function(e) {
  var current_text = $("#name").val();
  var cursor_position = $("#name")[0].selectionStart;
  var new_text = $(this).text();
  current_text = [current_text.slice(0, cursor_position), new_text, current_text.slice(cursor_position)].join('');
  $("#name").val(current_text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" id="name">

<!--Some keys-->
<div id="k-e" class="key key-btn">e</div>
<div id="k-r" class="key key-btn">r</div>
<div id="k-t" class="key key-btn">t</div>
showdev
  • 28,454
  • 37
  • 55
  • 73