yltang52 yltang52 - 2 years ago 72
Javascript Question

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.


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


$(document).on('keypress', '#abc', function(e) {
if (e.which!=13) {
console.log('Entered: ' + $('#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
(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.


  1. Why is that?

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download