Home > Net >  Javacript: How do you get the caret position and assign it to a variable?
Javacript: How do you get the caret position and assign it to a variable?

Time:08-05

So I'm attempting to create an if/else statement, where the console logs a statement if the enter key is pressed and if the caret has a certain position in an input field. What I can't figure out is how to detect where the caret is positioned and then assign that to a variable.

I have tried windows.getSelection() But this doesn't appear to do anything. Does anyone know how to do this in Javascript?

CodePudding user response:

You can use indexOf on the value of your input to find the index of searched character in a string.

This example outputs it in the console but you could set it to any variable you want.

var input = document.getElementById("myInput");
input.addEventListener("keypress", function(event) {
  if (event.key === "Enter") {
    event.preventDefault();
    console.log(document.getElementById("myInput").value.indexOf("^"));
  }
});

CodePudding user response:

Input fields have input.selectionStart and input.selectionEnd properties, if you don't select anything they return the position of the caret.

  • Related