I'm working on an input field where I need to disable the browser from
automatically doing this.select() on an input text field. In a nutshell,
I've got an input box I basically am treating like a masked input.

The reason is I'm manually pre-selecting a text range. If I invoke my
function to pre-select the correct text asynchronously (via setTimeout) it
works correctly, but you get a very brief flash as the browser natively does
a select() on the text already in the input field.

I've tried using both e.preventDefault() and e.stopPropagation(), but
neither stopped the behavior in FF. Returning "false" doesn't prevent the
behavior either.

Here's basically what the code looks like:

$("input#myField").bind("focus", function (){
  setTimeout(function (){
    // preselect just the first 2 chars
    setSelection(this, 0, 2);
  }, 0);
});

// set the text selected in a text field
function setSelection(field, start, end) {
  if( field.createTextRange ){
    var selRange = field.createTextRange();
    selRange.collapse(true);
    selRange.moveStart("character", start);
    selRange.moveEnd("character", end);
    selRange.select();
  } else if( field.setSelectionRange ){
    field.setSelectionRange(start, end);
  } else {
    if( field.selectionStart ){
      field.selectionStart = start;
      field.selectionEnd = end;
    }
  }
  field.focus();
};

Does anyone know of a trick to completely prevent FF from trying to select
all the text in a field automatically?

-Dan

Reply via email to