Goose Goose - 7 months ago 6
Javascript Question

Have user selection a certain point of text input with javascript/jquery

I have a text input.

<input type="text" id="foo" name="bar" value="11 Minutes"/>


11 Minutes

I want it so when the user clicks on the input, that the user's "Cursor" or "Selector" is after the 11, not after the Minutes.

I do not know where to begin, if this is possible across browsers, and have been unable to find information on this.

Decent browser support should be considered as well.

Answer

Try this, I don't know if this will work for you . but basically I'm setting the selectionStart and selectionEnd on where do you want the cursor to be placed.

You can also play with the selectionStart and selectionEnd. adding range between those two would result too highlighted selections. Just make it sure that start < end and you're good.

$(document).on("click", function(e){
  if (e.target && e.target.id == "foo") {
    if ($(e.target).is(":focus")) {
      e.target.selectionStart = 2;
      e.target.selectionEnd = 2;
    }
  }
  
});
<input type="text" id="foo" name="bar" value="11 Minutes"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Comments