javascriptselectcjkexeccommand

How do I select the last character of a string, using JavaScript?


I have a function that gets the last character of a string the user types in an input. But how do I select that single character, using execCommand()? The goal is to copy it into a different input.

I tried element.select(), but with no results.

The character to paste into the new input must be the character visible in the original input, and not the character correspondent to the keyboard key the user types, since the reason for all this is having an external JS library handling some CJK character conversion in one input, and moving the result to a different one..

I am going with a copy-paste approach. Hence, the need to select the character. But if there is a better way to achieve it, feel free to tell me about it.

I am open to both Vanilla JavaScript and jQuery approaches.

This is my code:

JSFiddle

function copyPaste () {
  var i1 = document.getElementById('userInput');
  var i2 = document.getElementById('input2');
  var c = i1.value.substr(lol.length - 1);
  c.select();
  document.execCommand('copy');
  i2.focus();
  document.execCommand('paste');
  i1.focus();
}
input {
  width: 255px;
}
  
button {
  display: block;
  margin: 20px 0;
  text-align: left;
}
<input type="text" id="userInput" placeholder="First, type something here.">

<button type="button" onclick="copyPaste"();>Then, click here to copy the last character<br>of the above input into the next input.</button>

<input type="text" id="input2" value="Some text...">


Solution

  • You should not use execCommand as it is obsolete. Moreover, you don't need to use the clipboard to transfer a (part of a) string to another input box. This can be done with standard string handling:

    var input = document.getElementById('userInput');
    var output = document.getElementById('input2');
    var btn = document.querySelector('button');
    
    btn.addEventListener("click", function () {
      output.value += input.value.slice(-1);
    });
    input {
      width: 255px;
    }
      
    button {
      display: block;
      margin: 20px 0;
      text-align: left;
    }
    <input type="text" id="userInput" placeholder="First, type something here.">
    
    <button type="button">Then, click here</button>
    
    <input type="text" id="input2" value="Some text...">