Mjukis Mjukis - 1 year ago 66
Javascript Question

Select first character of input value with Jquery

I have some input fields that are pre-filled thru Jquery.

I'd like to grab the value of an input, check if it start with "x" and if it does, select that x. (So that the user can quickly change the x by just typing something else)

I know there is a question like this here:

Selecting Part of String inside an Input Box with jQuery

But it's an really old question and it doesn't really use Jquery!

So, how can i select the x in this input's value?

<input class="input" type="text" value="x*500*500" />

I tried:

var input = $('.input');
input.setSelectionRange(0, 2); // Highlights "X"

Uncaught TypeError: input.setSelectionRange is not a function


Answer Source

You must dereference the jQuery object by adding [0]. setSelectionRange is plain JavaScript and deals with plain JS objects. It doesn't know what a jQuery object is. BTW, I changed the second parameter from 2 to 1. It's not behaving like MDN has described?


var input = $('.input')[0];
input.setSelectionRange(0, 1); // Highlights "X"
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="input" type="text" value="x*500*500" />