0

I have form with lot's of date input fields. I would only like to select firs two characters of date (e.g. day portion of the date only) when focusing on a input field. I have accomplished this with this code:

$(".date").focus(function() {
  this.setSelectionRange(0, 2);
});

The problem is this only works if I focus on input field with a mouse click. But if moving between input fields with TABULAR key on keyboard then the entire text in input field is selected. Can this be controlled via JavaScript as well?

Here is also JSFiddle which demonstrates above.

Primoz Rome
  • 10,379
  • 17
  • 76
  • 108

2 Answers2

0

It sounds like the default handler is being run after yours.

Prevent this by stopping the browser's default handler by running:

$(".date").focus(function(e) {
    e.preventDefault();
    this.setSelectionRange(0, 2);
});
Phylogenesis
  • 7,775
  • 19
  • 27
  • Haven't thought on this one but unfortunately does not help. It looks like it selects only first tho chars though, but then immediately selects entire string ... – Primoz Rome Feb 12 '14 at 17:09
  • @PrimozRome I've tested the changes as per http://jsfiddle.net/2KQXT/2/. It seems to work fine in IE11 and Firefox 27 but not in Chrome 32. – Phylogenesis Feb 12 '14 at 17:17
  • It appears that Chrome does not support `setSelectionRange()`. – Phylogenesis Feb 12 '14 at 17:23
  • Hmm yes it works on fiddle with Firefox, though not on my project code. Still figuring out what's causing the difference. – Primoz Rome Feb 12 '14 at 18:15
0

i posted here an answer, which is related to what you want , check it out: how-to-select-particular-text-in-textbox

Community
  • 1
  • 1
Amir Sherafatian
  • 2,083
  • 2
  • 20
  • 32