Search code examples
javascriptjqueryhtml-input

Input value returns an empty string due to input font-size="0"


I found a problem which has bothered me for several weeks. I am using jQuery to retrieve the input text. The user enters some characters and hits ENTER, and I print the text in console.

html:

<input id="abc" type="text" autofocus style="font-size:0;">

jQuery:

$(document).on('keypress', '#abc', function(e) {
  if (e.which!=13) { 
    return;
  }
  console.log('Entered: ' + $('#abc').val());
  $('#abc').val('');
});

If I use Firefox, everything is fine. However, if I use Chrome or Opera, they will return a empty string.

I finally found out that the problem comes from font-size="0" (I want to hide the input). If the value is anything other than 0, Chrome and Opera will have no problem picking up the entered text.

Questions:

  1. Why is that?

  2. How do I hide the <input> element and it can still take user inputs?


Solution

  • To answer your second question, you can use CSS styles such as text-indent. The text will be hidden offscreen and you'll stilll be able to get the value.

    <input id="abc" type="text" autofocus style="text-indent:-9999em;">
    

    I do believe that there are other ways to achieve this... like positioning the input offscreen

    <input id="abc" type="text" autofocus style="position:absolute; left:-9999em; top:-9999em"> 
    

    but your project seems pretty specific.