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

4 comments:

  1. The blog is so beautiful,and the articles is great!It' s so usful to me ,thanks very much!Buy WOW GoldLet me tell you a joke:One day a pregnant women across the road was a police stopped, then pregnant women say: 'why are you hold me? I first did not run a red light, the second Cheap Runescape Gold
    I get zebra crossing, the third I not line pressing, what makes you sent me the money! "
    Police said: "you overload!"Buy Diablo 3 Gold

    ReplyDelete
  2. 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
  3. When you're down, and the world seems dark and empty, your forever friend lifts you up in spirits and makes that dark and empty world suddenly seem bright and full Diablo iii Gold Sale, this is Forever Friendship Diablo III Gold, someone who convinces you that there really is an unlocked door just waiting for you to open it Diablo 3 Gold.

    ReplyDelete
  4. 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