Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the focus on a hidden textbox field using JavaScript?

How can I set the focus on a hidden textbox element?

I tried this:

document.getElementById("textControl_fd_component_JSON_TASK_NStext64").focus();  

But, this does not work here. As alert(document.activeElement.id); returns null in this case.

If I make this field visible, the above script works fine. Any ideas where I am getting it wrong?

like image 439
Pramod Kumar Avatar asked Jun 01 '12 13:06

Pramod Kumar


People also ask

How can you specify focus in an input field?

To set focus to an HTML form element, the focus() method of JavaScript can be used. To do so, call this method on an object of the element that is to be focused, as shown in the example. Example 1: The focus() method is set to the input tag when user clicks on Focus button.

What is focus () JavaScript?

focus() Javascript focus() methods helps to highlight a HTML form element. It sets the element as an active element in the current document. In current documentation, focus can be applied to only one single element. The focus can be applied either to a text, a button, etc.


1 Answers

If you really need to do this, make the box transparent, not hidden:

opacity:0; filter:alpha(opacity=0); 

Alternatively, if you want to ensure that the user doesn't accidentally click it, just place the input inside a div with

width: 0; overflow: hidden; 

However, there is most certainly a better way to do what you want, maybe using keydown/keypress events.

like image 82
apsillers Avatar answered Sep 25 '22 06:09

apsillers