2

I want to add a number in input field on button click and set the cursor position at the end of text. this should happen every time when the button is clicked.

<input id="input"></input>
<button onclick="addnumber()">add</button>
addnumber(){

}
  • Does this answer your question? [put cursor at end of text input's value](https://stackoverflow.com/questions/17780756/put-cursor-at-end-of-text-inputs-value) – lusc Jan 08 '22 at 13:35
  • @lusc i have tried this code but this doesnt work with button click – Dhruv Dhing Jan 08 '22 at 13:56

3 Answers3

1

JS code :

let input = document.getElementById('input')
function addnumber() {
  input.focus(); 
  var val = this.input.value; 
  input.value = ''; 
  input.value = val;
}

HTML code:

  <input id="input">
  <button onclick="addnumber()">add</button>
nagendra nag
  • 1,142
  • 2
  • 15
0
<input id="input"></input>
<button onclick="addnumber()">add</button>
    
<script>
    function addnumber() {
        const myInput = document.getElementById('input');
        const textLength = myInput.value.length;

        myInput.focus();
        myInput.setSelectionRange(textLength, textLength);
    }
</script>
  • this code is working but first the cursor goes at the starting position of input text then comes to the end of text. i want it to stay at the text end only – Dhruv Dhing Jan 09 '22 at 07:16
0

let input = document.getElementById('input')
function addnumber() {
  input.value=69
  input.focus()
}
<input id="input">
<button onclick="addnumber()">add</button>
Smollet777
  • 1,618
  • 1
  • 16
  • 15