Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery focus an element

Tags:

In javascript the following works to give focus to the edit_2 input box:

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

However using Jquery this does not:

$("#edit_2").focus; 
like image 996
stealthcopter Avatar asked Apr 24 '10 10:04

stealthcopter


People also ask

How do you set focus to a specific element?

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 event in jQuery?

The focus event occurs when an element gets focus (when selected by a mouse click or by "tab-navigating" to it). The focus() method triggers the focus event, or attaches a function to run when a focus event occurs. Tip: This method is often used together with the blur() method.

What is a focus element?

The focused element is the element that will receive keyboard and similar events by default. By default the browser will scroll the element into view after focusing it, and it may also provide visible indication of the focused element (typically by displaying a "focus ring" around the element).

Does focus scroll to Element?

An element can be focused by either using the autofocus="true" attribute or calling the element. focus() method. In both cases, the browser will automatically scroll the element into the viewport.


2 Answers

You are calling a method, so:

$("#edit_2").focus; 

should be

$("#edit_2").focus(); 

EDIT: If you are wondering why the first line was not counted as a syntax error, it's because it is a correct statement saying "get the function focus" (and do nothing with it).

like image 198
Alex Bagnolini Avatar answered Sep 18 '22 13:09

Alex Bagnolini


Your statement

$("#edit_2").focus 

is not calling the function 'focus', in order to call the function you have to use the syntax 'focus()'

try

j$("#some_id").focus() 

It is working fine.

EDIT Your statement '$("#edit_2").focus' is not throwing an error because it just returns a reference to the function 'focus', but it does not call the function.

like image 36
Arun P Johny Avatar answered Sep 18 '22 13:09

Arun P Johny