SoFunction
Updated on 2025-02-28

jquery focus text box and extended text box focus method

The cursor focuses at the front
Copy the codeThe code is as follows:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http:///TR/xhtml1/DTD/">
<html xmlns="http:///1999/xhtml">
<head>
<title>jquery Focus Text Box - Me</title>
<script src="/ajax/libs/jquery/1.4.2/" type="text/javascript"></script>
</head>
<body>
<form action="" >
<div>
<input type="hidden" name="cx" value="partner-pub-7740261255677392:7064996710" />
<input type="hidden" name="ie" value="UTF-8" />
<!--Text box--><input type="text" name="q" size="25" />
<input type="submit" name="sa" value="&#x641c;&#x7d22;" />
</div>
</form>
<script type="text/javascript">
$(document).ready(function () {
$("input[name='q']").focus();
})</script>
</body>
</html>


jquery extended text box focus method

In different browsers, if you just set focus() directly to the text box, the cursor's focus position may be in the front. The following code extends a textFocus method to jquery, which is used to focus the text box and make the cursor at the end, using $("input").textFocus(). You can also pass in a digital parameter to set the position where the cursor is focused. If $("input").textFocus(2), the cursor is after the second character.
Copy the codeThe code is as follows:

(function($){
$.=function(v){
var range,len,v=v===undefined?0:parseInt(v);
(function(){
if($.){
range=(); //Text box creates scope
v===0?(false):("character",v); //Scope folding
(); //Select
}else{
len=;
v===0?(len,len):(v,v); //dom directly set the selection, and then focus
}
();
});
return this;
}
})(jQuery)