1

I have a text box. When I write first text , then java script function will fire to check whether it is a number.

For IE , the following code is returning -1 value, But Other browsers it does not alert any value. Please help me

var selected = document.selection.createRange();
var decInSel = selected.text.indexOf('.');
hasNegInSel  = selected.text.indexOf('-') != -1;
alert(decInSel);
Manse
  • 37,765
  • 10
  • 83
  • 108
Suga24
  • 55
  • 1
  • 7

3 Answers3

1

document.selection.createRange() is IE < 9 only ... you the following function for cross browser support

function getSelectedText() {
  if (window.getSelection) {  // all browsers, except IE before version 9
    var selectionRange = window.getSelection ();                                        
    return selectionRange.toString();
  } else {
    if (document.selection.type == 'None') {
        return "";
    } else {
        var textRange = document.selection.createRange();
        return textRange.text;
    }
  }
}

Reference here

So your full code would look like this :

var selected = getSelectedText()
var decInSel = selected.indexOf('.');
hasNegInSel  = selected.indexOf('-') != -1;
alert(decInSel);
Manse
  • 37,765
  • 10
  • 83
  • 108
0

Use

window.getSelection()

Does chrome supports document.selection?

Community
  • 1
  • 1
davids
  • 6,259
  • 3
  • 29
  • 50
0

Other browsers use selectionStart and selectionEnd properties of the text box. You can get the selected text in a text box in those browsers using the following:

var input = document.getElementById("textBox");
var selectedText = input.value.slice(input.selectionStart, input.selectionEnd);
Tim Down
  • 318,141
  • 75
  • 454
  • 536