3

I have some input fields that are pre-filled through jQuery. I'd like to grab the value of an input, check if it starts 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 a 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"
input.focus();

error: Uncaught TypeError: input.setSelectionRange is not a function. Is setSelectionRangedeprecated?

dda
  • 6,030
  • 2
  • 25
  • 34
Björn C
  • 3,860
  • 10
  • 46
  • 85

3 Answers3

4

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?

SNIPPET

var input = $('.input')[0];
input.setSelectionRange(0, 1); // Highlights "X"
input.focus();
<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" />
Community
  • 1
  • 1
zer00ne
  • 41,936
  • 6
  • 41
  • 68
  • Thank u. This works like a charm. I'm not so familiar with plain JS. The second parameter was 2, because i was testing other settings. – Björn C Oct 27 '16 at 12:09
  • Oh, but if you look at the link I posted, you did it correctly according to MDN, yet it's not behaving as expected...a bug perhaps? Anyways, I'm glad I could help. Wait derp, I must be tired, MDN's description was correct. – zer00ne Oct 27 '16 at 12:12
  • Yeah, that's odd. Maby a bug or a typo. Oh.. wait..haha, me to.. it starts AFTER 2 ;D – Björn C Oct 27 '16 at 12:15
1

you are taking the complete element as in the input variable, take the value of input field and check if it starts with a character

var input = $('.input').val();
if(input.str.startsWith('X')){
    e.focus();
    var pos = e.val().indexOf('x');
    e.prop({
        'selectionStart': pos,
        'selectionEnd': pos + 1
    });
}
RAUSHAN KUMAR
  • 5,846
  • 4
  • 34
  • 70
1

var e = $('[data-field=test]');
setTimeout(function () {
  e.focus();
  var pos = e.val().indexOf('x');
  e.prop({
    'selectionStart': pos,
    'selectionEnd': pos + 1
  });
}, 100);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input data-field="test" value="hello x 123">
Keith
  • 22,005
  • 2
  • 27
  • 44