SoFunction
Updated on 2025-02-28

How to get text box focus and lose focus in js(jquery)

Let's first look at the JavaScript and write it directly on the input

Copy the codeThe code is as follows:

<input name="pwuser" type="text" class="input" value="Property account" onBlur="if(=='') ='Property account';" onFocus="if(=='Property account') ='';" />
<input name="pwpwd" type="password" class="input1" value="******" onBlur="if(=='') ='******';" onFocus="if(=='******') ='';">

jquery implementation method

For the focus event of an element, we can use jQuery's focus functions focus() and blur().

focus(): Used when you get focus, the same method as onfocus in javascript.
like:
Copy the codeThe code is as follows:

$("p").focus(); or $("p").focus(fn)

blur(): Used when the focus is lost, the same as onblur.
like:
Copy the codeThe code is as follows:

$("p").blur(); or $("p").blur(fn)

Example
Copy the codeThe code is as follows:

<form>
<label for="searchKey" >SearchShenma? </label> Here label is overlaid on the text box, allowing better control of styles
<input type="text" />
<input type="submit" value="Search" />
</form>

jquery code
Copy the codeThe code is as follows:

$(function() {
$('#searchKey').focus(function() {
$('#lbSearch').text('');
});
$('#searchKey').blur(function() {
var str = $(this).val();
str = $.trim(str);
if(str == '')
$('#lbSearch').text('Search Shenma?');
});
})

OK, pretty good