ballBreaker
ballBreaker

Reputation: 722

HTML Input Text select() method not working with Chrome

ISSUE:

I have legacy code that runs with IE that I am trying to make cross-browser compatible. One of the features I have been struggling to get working on modern browsers (Chrome in particular) is the .select() function on Input Text. Currently users enter in a value into a field, and then hit the "find on page" button, and the relevant text will be highlighted in the table below.

Internet Explorer:

Working select() functionality in IE

Google Chrome:

Broken select() in Chrome

As you can see above, in Chrome, the text is not highlighted. Leading me to believe that the select() functionality is NOT supported in Chrome. However, according to https://www.w3schools.com/jsref/met_text_select.asp this function is supported by Chrome.

RELEVANT CODE:

HTML Button for text selection:

<td align="center"><input type="text" name="textSearchInput" onkeypress="if (event.keyCode == 13) {textSearch(textSearchInput.value); return false;}" size="15" maxlength="30"><button type="button" id="formSubmit2" onclick="textSearch(textSearchInput.value);"><bean:message key="fp.inventory.textSearch"/></button></td>

JavaScript for searching and highlighting that WORKS in Internet Explorer but DOES NOT work in Chrome:

      var oRange = null;

      function textSearch(str)
      {
        if ((str == null) || (str == ''))
          return;

        if (oRange == null)
        { // first entry, or wrap search from the end
          oRange = document.body.createTextRange();
        }
        else
        { // move caret forward
          oRange.move('character', 1);
        }
        var found = oRange.findText(str);
        if (found)
        { // highlight and scroll to there
          oRange.focus();
          oRange.select();
          oRange.scrollIntoView(false);
        }
        else
        { // see if str exists at all by going backward
          found = oRange.findText(str, -1);
          if (found)
          { // wrap search
            oRange = null;
            textSearch(str);
          }
        }

Is there anything else that I am missing from this? I am not the most well-versed in either HTML or JavaScript so I could be missing something basic..

Upvotes: 1

Views: 1096

Answers (1)

Dave S
Dave S

Reputation: 3468

createTextRange is not supported in Chrome

http://help.dottoro.com/ljouisvm.php

You'll need to detect the browser and use an alternative.

This may work: https://developer.mozilla.org/en-US/docs/Web/API/Document/createRange

Upvotes: 2

Related Questions