In this article, we will learn how to prevent a textfield or an input from losing focus using jQuery. This can be used in situations where user validation is required. There are two approaches that can be taken:
Approach 1: We will be using the jQuery bind(), val(), preventDefault() and focus() methods. The bind() method is used to attach a “focusout” event to the textfield element. A helper function isValidString() is then created which helps us to validate the user input in the textfield. The function returns true if the string is “geeks” and false otherwise. The value of the textfield is extracted using the val() method and is used as a parameter in the isValidString() function. If the function returns false, then we prevent the default action of the “focusout” event using preventDefault() which means that the textfield will not lose focus. As soon the input in the textfield is “geeks”, the control flow goes outside the “if” statement and the default action of the “focusout” event is restored which means the textfield can lose focus.
Example: Here, the textfield will not lose focus even if we click outside the textfield if the input in the textfield is not the word “geeks“.
Approach 2: We will be using the jQuery bind(), val(), preventDefault() and focus() methods. This approach is similar to the previous approach but the difference is that the event that is attached to the textfield element is “blur” instead of “focusout“. The “blur” event is similar to the “focusout” event but the key distinction is that the “blur” event does not bubble. Therefore, if there is a requirement of finding out whether an element or its child loses focus, the “focusout“event should be used.
Please Login to comment...