Home >Web Front-end >JS Tutorial >How to get and lose focus events in jquery

How to get and lose focus events in jquery

青灯夜游
青灯夜游Original
2021-11-19 10:42:1512915browse

In jquery, you can use the focus() method to obtain the focus event, the syntax "$(selector).focus()"; you can use the blur() method to lose the focus event, the syntax "$(selector).blur ()".

How to get and lose focus events in jquery

The operating environment of this tutorial: windows7 system, jquery1.10.2 version, Dell G3 computer.

If there are some form elements in the front-end website that allow users to fill in the content, we can use the focus event and focus loss event in JQ to give the user some prompts. Today we will talk about how to use focus-getting and focus-losing events under JQuery.

jquery focus() Get focus event

focus() method: When an element is selected by clicking the mouse or positioned by the tab key, the element will gain focus.

Syntax:

$(selector).focus()

Copy

Example: The input input box changes the color of its border when it gets focus

Sample code:

<input type="text" name="" id="mochu">
<script>
    $(&#39;#mochu&#39;).focus(function(){
        $(this).css(&#39;border-color&#39;,&#39;red&#39;);
    });
</script>

Copy

When the mouse moves into the input and clicks, the input element will change into the following form

jq focus() event will add a CSS style to the input

<input type="text" name="" id="mochu" style="border-color: red;">

Copy

jquery blur() loses focus event

blur() method: The blur event occurs when the element loses focus

Syntax :

$(selector).blur()

Copy

Example: After input loses focus, the content in the input box pops up

Sample code:

<input type="text" name="" id="mochu">
<script>
    $(&#39;#mochu&#39;).blur(function(){ 
    alert($(this).val());    
    });
 </script>

Copy

The running results are as shown in the figure:

How to get and lose focus events in jquery

Use the jq blur() lost focus event to verify the content entered by the user

The blur() lost focus event in JQuery , we can use it to check whether the content entered by the user in the input input box is legal. For example, the following code will give a prompt if the content entered by the user is less than five characters

Sample code:

<input type="text" name="" id="mochu">
<script>
    $(&#39;#mochu&#39;).blur(function(){
        if($(this).val().length < 5){
            alert(&#39;字数太少了,多输入几个吧&#39;);
        }
    });
</script>

Related tutorial recommendations: jQuery video tutorial

The above is the detailed content of How to get and lose focus events in jquery. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn