Search code examples
htmlgoogle-chromefirefoxtextselection

No text selection in input box inside anchor in Firefox


If a text input tag is placed inside an anchor, then in Firefox (on Windows) it is not possible to manipulate text inside the text box — text cursor doesn't change its position, and it is not possible to select the text. In Chrome you can change cursor position, but not select the text.

In some cases we can set the parent to be something else than anchor, yet is there a way to avoid this behaviour in general?

Here's the HTML code:

<p>No text select in FF:</p>
<a href="#">
   <input type="text" value="7777" />
</a>

<p>Working text select in FF:</p>
<span>
   <input type="text" value="8888" />
</span>

And the fiddle.


Solution

  • You can remove the href attribute when the input element is focused. As long as there is no href attribute, you will be able to select text inside the input field (tested in safari, chrome and firefox).

    <a href="http://www.google.de" id="link">
      link
      <input type="text" id="input">
    </a>
    
    (function () {
      var link = document.getElementById('link');
      var input = document.getElementById('input');
    
      var saveHref = null;
    
      input.addEventListener('focusin', function () {
          savedHref = link.href;
          link.removeAttribute('href');
      });
    
      input.addEventListener('focusout', function () {
          link.href = savedHref;
          savedHref = null;
      });
    
    })();
    

    Working example: http://codepen.io/jjd/pen/JYwLVr