Monday, February 27, 2012

How to set focus to textbox with jquery

jquery version 1.7.1

This article show you how to focus to a textbox on page.
below have function that you can copy it to your page be used to focus the textbox, just pass the id of textbox.

this function is very simple.

function changeFocus(id){
    var v = "#" + id;
    $(v).focus();
}

The demo have two textbox and two button,
When you click the Change Focus1 button the focus will go to the first textbox, 
click the Change Focus2 button the focus will go to the second textbox.

DEMO





Below is the source code:

<html>
<body>
<div class="demo">
<h2>DEMO</h2>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $("#t1").focus();
    $("#b1").click(function(){
        changeFocus('t1');
        return false;
    });
    $("#b2").click(function(){
        changeFocus('t2');
        return false;
    });
});
function changeFocus(id){
    var v = "#" + id;
    $(v).focus();
}
</script>
 <form id="myForm" method="post" action="">
    <input id="t1" type="text"/>
    <input id="t2" type="text"/>
    <br/><br/>
    <input id="b1" type="button" value="Change Focus1"/>
    <input id="b2" type="button" value="Change Focus2"/>
 </form>
 </div>
</body>
</html>

Related Articles
jquery disable button

2 comments:

  1. The past is gone and static. Nothing we can do will change it Runescape Gold, The past is gone and static. Nothing we can do will change it Buy Runescape Gold Sale, Everything we do will affect it RS Gold.

    ReplyDelete
  2. Hi
    its nice but if two text boxes haveing values that time it focus what happen ? in IE cursor goes to first character but in chrome it goes to last character.

    ReplyDelete