0

i need to set the Clint focus on my input filed <input type="text" name="fname" id="fname" onfocusout="myFunction8()"> onfoucseout, and i want it to focus at cirtain place on the input (for exaple, position 2: "he[cursor]llo")

function myFunction8()
         {
         var str = document.getElementById("fname")
         var l = str.length
         var l = 0
         var n = 0
         var d = 0
         var s=0
         if (l < 5) {
             //the carsure will be foucused in position 0
         }
         else {
             for (var i = 0; i < str.length; i++) {
                 if ((str.charAt(i)) = "@") {
                     l++;
                     n = i
                 }
                 if ((str.charAt(i)) = ".") {
                     d++
                     l = i
                 }
             }
         }
         if (l == 0) {
             //the carsure will be foucused in position 1
         }
          if (d == 0) {
             //the carsure will be foucused in position 3
         }
         if (l > 1) {
             //the carsure will be foucused in position n
         }
         if ((l - n) < 2) {
             //the carsure will be foucused in position n+1
         }
         if (n==0) {
             //the carsure will be foucused in position 0
         }
         if (l==0) {
             //the carsure will be foucused in position 0
         }


    }

note: this articel was not helful becuse it not using vanila js and: this one as well as this one was not helpful becuse they fouce non foucing the curscur on the input fhils, but not use the exact position

Aviv Aviv
  • 129
  • 1
  • 10
  • Possible duplicate of [Set keyboard caret position in html textbox](https://stackoverflow.com/questions/512528/set-keyboard-caret-position-in-html-textbox) – Randy Casburn Jan 31 '19 at 16:14

1 Answers1

0

checkout this one

 function setCaretPosition(ctrl, pos) {
  if (ctrl.setSelectionRange) {
     ctrl.focus();
     ctrl.setSelectionRange(pos, pos);
  } else if(ctrl.createTextRange) {  //this is for old browsers
     var range = ctrl.createTextRange();
     range.collapse(true);
     range.moveEnd('character', pos);
     range.moveStart('character', pos);
    range.select();
  }
}
myFunction8(){
  var input = document.getElementById('fname');
  setCaretPosition(input, length);  
}
Hrishi
  • 1,210
  • 1
  • 13
  • 25
  • where can i choose witch position to focus – Aviv Aviv Jan 31 '19 at 16:28
  • myFunction8(){ var input = document.getElementById('fname'); var input = document.getElementById('fname'); setCaretPosition(input, 3); } it will set cursor at position 3 – Hrishi Jan 31 '19 at 16:36