Afan
Afan

Reputation: 69

How to forcibly set focus on an input field?

How do you forcibly set focus on an html element(input field) when there is another input field in the same web page (which gets loaded later) and steals the focus from the other input field? This 2nd input field is a part of an iFrame.

Both the input fields are independent (no one is a parent of the other), so I am not able to use event.stopPropagation() method here.

Upvotes: 1

Views: 569

Answers (2)

dave
dave

Reputation: 64657

Just steal it back using the blur event the first time it is blurred, and refocus it using focus()

$("#my-input").one("blur", function() {
    $(this).focus();
});

https://jsfiddle.net/kcuL1aec/

And yes, that is .one and not .on, so that it only happens once.

Upvotes: 2

Pabs123
Pabs123

Reputation: 3435

Try using the Focus function. Once the document has fully loaded simply use your favourite selection function to grab the html element and just do element.focus()

Upvotes: 0

Related Questions